JS-隔行换色+鼠标移上去变色

<style>
    ul{
       list-style: none;
    }
</style>
<body>
        <ul>
            <li>111</li>
            <li>222</li>
            <li>333</li>
            <li>444</li>
            <li>555</li>
            <li>666</li>
        </ul>
 
    <script>
        //要操作li 先获取所有li
        var lis = document.querySelectorAll('li')
        console.log(lis);
    
    // for循环里的 变量 i  要用let 定义 !!!!!!!
    // 用var 有时会报错   
    // 1.隔行换色
        for(let i=0; i<=lis.length-1; i++){
            if(i%2===0){
              lis[i].style.backgroundColor = 'pink'
            }else{
                lis[i].style.backgroundColor = 'lightblue'
            }
    // 2.移上去变色
            lis[i].onmouseover = function(){
            // 这里要用  this
                this.style.backgroundColor = 'green'
            }
    // 3.移出变为原来的颜色
            lis[i].onmouseout = function(){
                if(i%2===0){
                 lis[i].style.backgroundColor = 'pink'
              }else{
                 lis[i].style.backgroundColor = 'lightblue'
              }
            }
        }
        
    </script>
</body>

猜你喜欢

转载自blog.csdn.net/weixin_45959965/article/details/128350153