Javascript 更改 Div 样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10071286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript change Div style
提问by Sandbox E
I want that part 1
onclick div style changes and part 2
again on click it comes back to normal. I tried doing so but I failed to achieve the part 2
results.
我希望part 1
onclick div 样式更改,然后part 2
再次单击它恢复正常。我尝试这样做,但未能达到part 2
结果。
Following is the Javascript code
以下是Javascript代码
function abc() {
document.getElementById("test").style.color="red";
}
After clicking the test div again, color should come back to defaulr color i.e. black...
再次单击测试 div 后,颜色应恢复为默认颜色,即黑色...
回答by Yehuda Shapira
function abc() {
var color = document.getElementById("test").style.color;
if (color === "red")
document.getElementById("test").style.color="black";
else
document.getElementById("test").style.color="red";
}
回答by Hymantheripper
Using jQuery:
使用jQuery:
$(document).ready(function(){
$('div').click(function(){
$(this).toggleClass('clicked');
});
});?
回答by Selvakumar Ponnusamy
Have some logic to check the color or have some flag,
有一些逻辑来检查颜色或有一些标志,
function abc() {
var currentColor = document.getElementById("test").style.color;
if(currentColor == 'red'){
document.getElementById("test").style.color="black";
}else{
document.getElementById("test").style.color="red";
}
}
回答by faino
A simple switch statement should do the trick:
一个简单的 switch 语句应该可以解决问题:
function abc() {
var elem=document.getElementById('test'),color;
switch(elem.style.color) {
case('red'):
color='black';
break;
case('black'):
default:
color='red';
}
elem.style.color=color;
}
回答by apnerve
function abc() {
var color = document.getElementById("test").style.color;
color = (color=="red") ? "black" : "red" ;
document.getElementById("test").style.color= color;
}
回答by Vlad
Better change the class of the element (.regular is black, .alert is red):
更好地改变元素的类(.regular 是黑色,.alert 是红色):
function abc(){
var myDiv = document.getElementById("test");
if (myDiv.className == 'alert') {
myDiv.className = 'regular';
} else {
myDiv.className = 'alert';
}
}
回答by lioncin
you may check the color before you click to change it.
您可以在单击更改颜色之前检查颜色。
function abc(){
var color = document.getElementById("test").style.color;
if(color==''){
//change
}else{
//change back
}
}