来回更改样式 [英] Change style back and forth
问题描述
代码:
<style> .demo {color: yellow; background-color: purple} </style>
<p class="demo">my text</p>
<button id="change">click</button>
<script>
window.onload = function () {
var flipColors = query("#change");
var target = query(".demo");
flipColors.onclick = function() {
style(target, "color", "white");
style(target, "background-color", "black");
};
};
</script>
当我单击按钮时,样式会更改.
When I click the button the style changes.
我的问题是当按钮添加到JS时我需要添加什么再次单击-它会恢复原始样式,如果再次单击它,则会重新激活该功能,而不用单击两个按钮.
My question is what do I need to add to the JS that when the button clickes again - it would restore the original style, and if it is clicked again it will activate the function again, instead of making two buttons.
我知道我可以创建 .demo
和 .demo1
类并进行切换,但是我想了解如何做到这一点-如果可能的话.
I know that I can create .demo
and .demo1
classes and switch them, but I want to understand how to make it that way - if it is possible.
注意:只是普通的JS,不是JQuery等.
Note: Just plain JS, not JQuery etc.
推荐答案
是的,toggle()在这里效果很好.我确实创建了两个切换类,而javascript最初只是打开了一个,然后切换了两个状态.
yup, the toggle() works wonderfully well here. I did create a two toggle classes, and the javascript simply turns one on initially, then toggles the two states.
var flipColors = query("#change");
var target = query(".demo");
target.classList.add("demo-on");
toggleClasses = function toggleClasses() {
target.classList.toggle("demo-on");
target.classList.toggle('demo-off');
};
.demo-off {
color: yellow;
background-color: purple;
}
.demo-on {
color: purple;
background-color: yellow;
}
<p class="demo">my text</p>
<button id="change" onclick="toggleClasses()">click</button>
嗯,但是您实际上不想切换类,但是要切换CSS属性?轻松完成.试试这个:
Ah, but you don't want to actually toggle the classes, but the css attributes? Easily done. Try this one:
var theToggle = document.getElementById("change");
var toggleMe = document.getElementsByClassName("demo")[0];
toggleMe.toggleStatus = "on";
theToggle.onclick = function(){
switch(toggleMe.toggleStatus){
case "on":
toggleMe.toggleStatus="off";
toggleMe.style.color = "purple";
toggleMe.style.backgroundColor = "yellow";
break;
case "off":
toggleMe.toggleStatus="on";
toggleMe.style.color = "yellow";
toggleMe.style.backgroundColor = "purple";
break;
}
}
.demo {
width: 100px;
height: 100px;
color: yellow;
background-color: purple
}
<p class="demo">my text</p>
<button id="change">click</button>
这是纯js,我添加了一个用于检查要使用的状态的属性,但是您可以轻松地运行switch语句,例如toggleMe.style.color-希望对您有所帮助!
This is pure js, I'm adding a property that I use to check which status to use but you could just as easily run the switch statement off, for example, toggleMe.style.color -- Hope this helps!
这篇关于来回更改样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!