JavaScript--this的小栗子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        li{
            width: 50px;
            height: 50px;
            background: red;
            text-align: center;
            font:30px/60px "simhei";
            margin-right:5px;
            color: #fff;
            border-radius: 50%;
            float: left;
            list-style: none;
            position: relative;
            left: 0;
            top: 0;
            transition: 0.8s;
        }
        ul{
            width: 275px;
            margin:auto auto;
            /*overflow: hidden;*/

        }
        .active{
            background: #fff;
            color: #000;
            border:1px solid red;
            top:100px;
        }
    </style>
    <script type="text/javascript">
        window.onload = function(){
            var aLi = document.getElementsByTagName("li");
            var that = null;

            for(var i=0; i<aLi.length; i++){
                aLi[i].onclick = function(){
                    that = this;
                    fn1();
                }           
            }
            function fn1(){
                //这个for循环用来清除格式
                for(var i=0; i<aLi.length; i++){
                    aLi[i].className = "";
                }
                that.className = "active";
            }
    }

    /*
        window.onload = function(){
            var aLi = document.getElementsByTagName("li");

            for(var i=0; i<aLi.length; i++){
                aLi[i].onclick = fn1;           
            }
            function fn1(){
                //这个for循环用来清除格式
                for(var i=0; i<aLi.length; i++){
                    aLi[i].className = "";
                }
                this.className = "active";
            }
    }
    */
    </script>
</head>
<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>
</body>
</html>

显示结果

这里写图片描述

这里写图片描述

这里写图片描述

猜你喜欢

转载自blog.csdn.net/baidu_37181928/article/details/78725523