<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>点击改变背景颜色</title>
<script language="javascript">
function changecolor(){
x = document.getElementById("odiv");
x.style.background="#000000"?"#ffffff":"#000000";
}
</script>
<style type="text/css">
*{
margin:0;
padding:0;
}
#odiv{
width:100px;
height:100px;
background:#0F0;
border:2px solid #000000;
}
</style>
</head><body>
<a href="#" onclick="changecolor()">链接</a>
<div id="odiv"></div>
</body>
</html>第一次点击链接#odiv的背景颜色可以改变,为什么以后的点击脚本不会执行呢
第二次进去还是不会成立因为 获取到的是 “none repeat scroll 0% 0% rbg(0,0,0,)”
样式属性不是你放进去什么值 获取出来就是什么值,它有它自己的一套解析方式。
所次 你每次点击 都会改变成 #000000 其实代码是一直执行的 只是没效果而已
function changecolor(){
x = document.getElementById("odiv");
x.style.backgroundColor=x.style.backgroundColor.toString()=="#000000"?"#ffffff":"#000000";
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>点击改变背景颜色</title>
<script language="javascript">
function changecolor(){
x = document.getElementById("odiv");
alert(x.style.backgroundColor);
x.style.backgroundColor = x.style.backgroundColor == "rgb(255, 255, 255)"?"#000000":"#ffffff";
}
</script>
<style type="text/css">
*{
margin:0;
padding:0;
}
#odiv{
width:100px;
height:100px;
background:#0F0;
border:2px solid #000000;
}
</style>
</head><body>
<a href="#" onclick="changecolor()">链接</a>
<div id="odiv"></div>
</body>
</html>
ie 输出 #ffffff
firefox 输出 rgb(255, 255, 255)
所以要判断一下
你在控制颜色的变换时。再仔细看看。。用if语句判断试试
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8" />
<title>点击改变背景颜色</title>
<script language="javascript">
function changecolor(){
x = document.getElementById("odiv");
x.style.backgroundColor=x.style.backgroundColor.toString()=="#000000"?"#ffffff":"#000000";
}
</script>
<style type="text/css">
*{
margin:0;
padding:0;
}
#odiv{
width:100px;
height:100px;
background:#000000;
border:2px solid #000000;
}
</style>
</head><body>
<a href="#" onclick="changecolor()">链接</a>
<div id="odiv"></div>
</body>
</html>你看你想达到的是这种效果吗?
你要的是color
alert(x.style.backgroundColor);
x = document.getElementById("odiv");
x.style.backgroundColor=x.style.backgroundColor.toString()=="#000000"?"#ffffff":"#000000";
}
function changecolor(){
var x = document.getElementById("odiv");
x.style.background=(count++)%2==0?"#ffffff":"#000000";
}