[英]addEventListener not working for toggle button
我正在研究Flask中的一項功能,以在深色和淺色主題之間切換。 我在單獨的文件中使用 Flask、CSS 和 Javascript。 單擊切換按鈕時,不會更改 css 樣式表。
application
├── static
│ ├── css
│ | ├── base-theme.css
│ | ├── dark-theme.css
│ └── js
│ ├── switch_themes.js
├── templates
│ ├── base.html
底座.html
!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Application</title>
<meta name="description" content="Application">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{{ url_for('static', filename='css/base-theme.css') }}" id="switch_theme">
<script type="text/javascript" src="{{ url_for('static', filename='js/switch_themes.js') }}"></script>
</head>
<body>
<div class="topnav">
<table class="topnav_right">
<tbody>
<tr>
<td>
<div class="topnav_theme">
<table>
<tbody>
<tr>
<td><a class="theme" href="/">THEME</a></td>
</tr>
</tbody>
</table>
</div>
</td>
<td>
<div class="topnav_mode">
<table>
<tbody>
<tr>
<td>
<button id="btn-toggle">
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</tr>
</td>
</tbody>
</table>
</div>
{% block body %}{% endblock %}
</body>
</html>
switch_themes.js
window.onload = function () {
const toggle = document.getElementById("btn-toggle");
const theme = document.getElementById("switch_theme");
toggle.addEventListener("click", function () {
if (theme.getAttribute("href") == "/static/css/base-theme.css") {
theme.href = "/static/css/dark-theme.css";
} else {
theme.href = "/static/css/base-theme.css";
}
});
}
該應用程序可以正常工作(瀏覽器控制台中也沒有錯誤),但是單擊切換按鈕(btn-toggle)時不會切換主題。
此致,
馬丁
我解決了這個問題。
它實際上可以工作,但是<button>
是多余的,並且由於<label>
和<span>
標簽,該按鈕的單擊區域太小。 我已經更改了下面的代碼,現在它可以工作了:
<td>
<label class="switch">
<input type="checkbox" id="btn-toggle">
<span class="slider"></span>
</label>
</td>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.