如何使用一个按钮切换此项,而不是使用addEventListener-click打开和关闭按钮?
由于
html代码:
<nav>
<ul>
<li id="first"><a href="#">Home</li>
</ul>
</nav>
<button id = "btn">Click to Open</button>
<button id = "btnRemove">Click to Close</button>
JS代码:
document.getElementById("btn").addEventListener("click", myFunction, false);
function myFunction() {
var x = document.getElementById("first");
x.style.transition = "all 2s ease";
x.style.background = "red";
x.style.borderBottom = "1px solid black";
x.style.width = "100px";
x.style.height = "100px";
};
document.getElementById("btnRemove").addEventListener("click", myFunction_remove, false);
function myFunction_remove() {
var y = document.getElementById("first");
y.style.transition = "all 2s ease";
y.style.background = "";
y.style.borderBottom = "";
y.style.width = "5px";
y.style.height = "15px";
};
答案 0 :(得分:0)
您可以更改按钮的状态以打开和关闭
这样的事情会起作用
document.getElementById("btn").addEventListener("click",function(event){
if(event.target.getAttribute("status")=="open"){
event.target.setAttribute("status","close")
/**/
}
else if(event.target.getAttribute("status")=="close"){
event.target.setAttribute("status","open")
/**/
}
else if(event.target.getAttribute("status")==null){
event.target.setAttribute("status","open")
/**/
}
},false);
答案 1 :(得分:0)
注意:您忘记在上面的代码中关闭应答器。
最好的方法是在css类中添加你的风格。
#first {
transition : all 2s ease;
background-color : auto;
borderBottom : 0px;
width : 5px;
height : 15px;
}
#first.activate {
background-color : red;
border-bottom : 1px solid black;
width : 100px;
height : 100px;
}
然后点击javascript按钮更改课程。
document.getElementById("btn").addEventListener("click", myFunction, false);
function myFunction() {
var x = document.getElementById("first");
x.className = (x.className === "activate") ? "" : "activate";
};
答案 2 :(得分:0)
在这里尝试使用给定的代码段
HTML
<div id="toggleArea" class='active'> Toggle area see in class name </div>
<button id="btnToggle"> Toggle Button </button>
JavaScript
const toggleArea = document.getElementById('toggleArea')
const btnToggle = document.getElementById('btnToggle')
btnToggle.addEventListener('click', function() {
if (toggleArea.classList.contains('active')) {
toggleArea.classList.remove("active");
toggleArea.classList.add("disable");
} else {
toggleArea.classList.remove("disable");
toggleArea.classList.add("active");
}
})