我需要切换 - 打开侦听单击,然后将切换框的类名称更改为“打开”。然后切换 - 关闭单击,然后将切换框的类名称更改为“关闭”。这是我已经存在的代码,它不起作用,有什么建议吗?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Drop Down</title>
<link rel="stylesheet" href="dropdown.css" type="text/css"/>
</head>
<body>
<div id="toggle-box" class="close">
<div id="toggle-open">Settings</div>
<div id="toggle-close">Close</div>
<ul>
<li>
<label for="s-1">
<input id="s-1" type="checkbox" checked>
<span>Setting One</span>
</label>
</li>
<li>
<label for="s-2">
<input id="s-2" type="checkbox" checked>
<span>Setting Two</span>
</label>
</li>
<li>
<label for="s-3">
<input id="s-3" type="checkbox">
<span>Setting Three</span>
</label>
</li>
<li>
<label for="s-4">
<input id="s-4" type="checkbox" checked>
<span>Setting Four</span>
</label>
</li>
<li>
<label for="s-5">
<input id="s-5" type="checkbox">
<span>Setting Five</span>
</label>
</li>
</ul>
</div>
<p style="margin-top: 100px; text-align: center; font-size: 75%;"><a href="../dropdown.zip">Download the files (dropdown.zip)</a></p>
<script src="dropdown.js"></script>
</body>
&GT;
答案 0 :(得分:0)
如果您可以将jquery javascript库添加到您的网页(只是一个&lt; script&gt;块),可以使用以下javascript完成:
$("#toggle-open").click(function() {
$("#toggle-box").attr("class", "open");
});
$("#toggle-close").click(function() {
$("#toggle-box").attr("class", "close");
});
没有jquery:
document.getElementById("toggle-open").addEventListener("click", function() {
document.getElementById("toggle-box").setAttribute("class", "open");
});
document.getElementById("toggle-close").addEventListener("click", function() {
document.getElementById("toggle-box").setAttribute("class", "close");
});
答案 1 :(得分:0)
不需要jQuery。
var toggleBox = document.getElementById('toggle-box');
document.getElementById('toggle-open').click = function() {
toggleBox.className = 'open';
};
document.getElementById('toggle-close').click = function() {
toggleBox.className = 'close';
};
答案 2 :(得分:0)
而不是行:
<script src="dropdown.js"></script>
在你的代码中你可以写:(你可以删除有警报的行(tooglebox.className);我只是为了测试。)
<script>
var settings = document.getElementById('toggle-open');
var close = document.getElementById('toggle-close');
var tooglebox = document.getElementById('toggle-box');
settings.onclick = function(){
tooglebox.className = "open";
alert(tooglebox.className);
}
close.onclick = function(){
tooglebox.className = "close";
alert(tooglebox.className);
}
</script>