Javascript更改Div样式
我希望Javascript更改Div样式,javascript,Javascript,我希望第1部分再次单击div样式更改,然后再次单击第2部分使其恢复正常。我尝试过这样做,但未能达到第2部分的结果 下面是Javascript代码 function abc() { document.getElementById("test").style.color="red"; } 再次单击测试div后,颜色应恢复为默认颜色,即黑色…您可以在单击更改颜色之前检查颜色 function abc() { var color = document.getElementById("t
第1部分
再次单击div样式更改,然后再次单击第2部分
使其恢复正常。我尝试过这样做,但未能达到第2部分的结果
下面是Javascript代码
function abc() {
document.getElementById("test").style.color="red";
}
再次单击测试div后,颜色应恢复为默认颜色,即黑色…您可以在单击更改颜色之前检查颜色
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";
}
function abc(){
var color = document.getElementById("test").style.color;
if(color==''){
//change
}else{
//change back
}
}
有一些逻辑来检查颜色或有一些标志
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";
}
}
一个简单的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;
}
最好更改元素的类(.regular为黑色,.alert为红色):
使用jQuery:
$(document).ready(function(){
$('div').click(function(){
$(this).toggleClass('clicked');
});
});
在你的if语句中,为什么不color=“black”
和color=“red”
。你已经拿着那本书了color@AbdullahGheithcolor
只是变量的名称。我可以给它取名为bob或者我想要的任何东西。我将颜色存储在color
中。我的意思是在if之后的行和if之后的行中else@AbdullahGheith在这些行中,我设置元素的颜色,而不是获得颜色。
function abc(){
var myDiv = document.getElementById("test");
if (myDiv.className == 'alert') {
myDiv.className = 'regular';
} else {
myDiv.className = 'alert';
}
}
$(document).ready(function(){
$('div').click(function(){
$(this).toggleClass('clicked');
});
});