用js写一个点击变绿色再点击一下变红色 可以这样写吗 刚开始学不懂

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>

#s1{
background-color:red;
width:300px;
height:300px;
}

#s2{
background-color:green;
width:300px;
height:300px;
}

</style>

</head>

<body>
<div id="s1" onClick="hg();"></div>
</body>

<script>

function hg(){
var div=document.getElementById('s1');
if (div.style.backgroundColor.indexOf("red")>=0)
{
div.id="s2";
}else{
div.id="s1";
}
}
</script>

</html>

这样有问题的,Id从s1变成s2的话,第二次点击就没办法通过s1找到这个元素了。
直接修改背景色就好了。

if (div.style.backgroundColor.indexOf("red")>=0)
{
div.style.background="green";
}else{
div.style.background="red";
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-12-05
也可以使用jquery的形式,导入所需要的jquery文件,然后给他添加class,addclass和removeclass这样的方法就可以实现切换
相似回答