js点击图片换颜色问题

 <!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>js学习</title>
<style>
#sq{
    width:400px;
    height:400px;
    background:#C25B5D;}
#sq1{
    width:400px;
    height:400px;
    background:blue;}
</style>
</head>
<body>
<div id="sq" onClick="ch();"></div>
</body>
<script>
 function ch(){
     var sq= document.getElementById('sq'); 
     if(sq.id.indexOf('sq') > -1){
     sq.id = "sq1";
     }else{
        sq.id = "sq"; 
         }
     }
</script>
</html>

有用记得采纳:)。。

 <!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>js学习</title>
    <style>
        #sq {
            width: 400px;
            height: 400px;
            background: #C25B5D;
        }

        #sq1 {
            width: 400px;
            height: 400px;
            background: blue;
        }
    </style>
</head>
<body>
    <div id="sq" onclick="ch();"></div>
</body>
<script>
    function ch() {
        var sq = document.getElementById('sq') || document.getElementById('sq1');//这里要做兼容,要不你改过id第一个就获取不到对象了
        sq.id = sq.id == 'sq' ? 'sq1' : 'sq';
    }
</script>
</html>

<!doctype html>



js学习 .sq{ width:400px; height:400px; background:#C25B5D;} .sq1{ width:400px; height:400px; background:blue;}




document.body.onclick=function(e){ var target = (e||event.srcelement).target; if(target.tagName == "DIV"){ target.className = target.className == 'sq'?'sq1':'sq'; } }

从题主本身编程来说,第一次变色,第二次不变色有两个原因。
1.改变了类名,导致第二次var sq= document.getElementById('sq'); 获取的为空。解决办法在全局获取dom对象
2.id改变,你的indexOf查找 sq和sq1均不等于-1,indexOf是查找是否有,和等于是有差别的。所有如果要用indexOf方法就得将两个类名改一下或者条件改一下

js代码如下

<script>
var sq= document.getElementById('sq');    // 提示为全局,即使后面类名变了,dom对象没变,依然可以对其操作
function ch(){
 if(sq.id.indexOf('1') > -1){      // 条件改为1,因为sq和sq1的差别是1 所有用1来做条件
 sq.id = "sq1";
 }else{
        sq.id = "sq"; 
        }
 }
</script>

一点建议,对于用js改变dom样式,应该使用类名改变,而不是id

  <!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>js学习</title>
<style>
#s{
    width:400px;
    height:400px;
}
.sq{
    background:#C25B5D;}
.sq1{
    background:blue;}
</style>
</head>
<body>
<div id="s" class="sq" onClick="ch();"></div>
</body>
<script>
var sq= document.getElementById('s'); 
function ch(){
    sq.className = sq.className.indexOf('1') > -1 ? 'sq' : 'sq1'
}
</script>
</html>