老师,教程里的点击按钮更换图片的代码存在浏览器兼容问题,在IE浏览器下可以,在火狐浏览器里面不行
来源:4-4 video-javascript(1)
慕仰6311720
2019-07-05 11:05:32
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>修改class</title>
<style>
*{
margin:0;
padding: 0;
}
.one{
margin:50px auto;
width: 400px;
height: 400px;
background: url(http://p3.so.qhimgs1.com/sdr/400__/t0168628d72562bbf03.jpg) ;
}
.two{
margin:50px auto;
width: 400px;
height: 400px;
background: url(http://p2.so.qhmsg.com/sdr/400__/t01021f81c7b56c7f37.jpg) ;
}
</style>
</head>
<body>
<div class="one"></div>
<script>
var btn = document.getElementsByIdName("one")[0],
name = true;
btn.onclick=function(){
name = !name;
if(name == false){
this.className = "two";
}else{
this.className = "one";
}
console.log(name);
}
</script>
</body>
</html>1回答
你好,代码中的问题:
1、通过class名获取元素是ByClassName,不是ByIdName哦。
2、window对象中有name属性,这里设置变量名称也是name,所以有了冲突,设置值为true或者false,都是字符串类型,不是布尔类型,与布尔类型的不相等。
参考修改:

自己重新修改测试下,祝学习愉快!
相似问题