0

我需要切换打开监听单击,然后将切换框的类名更改为“打开”。然后让切换关闭听一下点击,然后将切换框的类名更改为“关闭”。这是我已经拥有的代码,但它不起作用,有什么建议吗?

<!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>

>

4

3 回答 3

0

如果您可以将jquery javascript 库添加到您的页面(只需再添加一个 <script> 块),则可以使用以下 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");
});
于 2013-10-31T22:03:57.747 回答
0

而不是行:

<script src="dropdown.js"></script> 

在您的代码中,您可以编写:(您可以删除包含 alert(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>
于 2013-10-31T22:37:37.940 回答
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';
};
于 2013-10-31T22:29:58.803 回答