点击链接scrollTop滚动条移动

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
             *{     margin: 0;    }
            ul{    width: 100%;height: 30px;position: fixed;display: none;}
            ul li{float: left;list-style: none;width: 250px;height: 30px;
                text-align: center;font-family: "微软雅黑";font-size: 20px;
                color: white;}
            div{width: 100%;
                height: 500px;
                text-align: center;
                font-size: 50px;
                line-height: 500px;
            }
            #btn{
                position: fixed;
                right: 0;
                bottom: 0;
                height: 50px;
                font-family: "微软雅黑";
                font-size: 18px;
                display: none;
            }
        </style>
    </head>
    <body>
        <ul id="ul1">
            <li style="background-color: red;" class="li1">1</li>
            <li style="background-color: black;" class="li1">2</li>
            <li style="background-color: blue;" class="li1">3</li>
            <li style="background-color: pink;" class="li1">4</li>
            <li style="background-color: green;" class="li1">5</li>
        </ul>
        <div class="diva" style="background:red;">红色区域</div>
        <div class="diva" style="background:black;">黑色区域</div>
        <div class="diva" style="background:blue;">蓝色区域</div>
        <div class="diva" style="background:pink;">粉色区域</div>
        <div class="diva" style="background:green;">绿色区域</div>
        <button id="btn">返回顶部</button>
        <script>
        /*
         原理:
           每次点击li时让li的高度值等于每个对应的div的scrollTop值
         * */
        window.onscroll = function (){
            var oUl = document.getElementById('ul1');
            var lis = document.getElementsByClassName('li1');
            var divs = document.getElementsByClassName('diva');
            var oBtn = document.getElementById('btn');
            var oScroll = document.documentElement.scrollTop||document.body.scrollTop;
            if(oScroll>200){
                oUl.style.display = 'block';
                oBtn.style.display = 'block';
            }else{
                oUl.style.display = 'none';
                oBtn.style.display = 'none';
            }
            oBtn.onclick = function (){
                document.documentElement.scrollTop = document.body.scrollTop = 0;
            }
            for (var i=0;i<lis.length;i++) {
                lis[i].index = i;//获取每一个li的索引下标
                lis[i].onclick = function (){
                    document.documentElement.scrollTop = document.body.scrollTop = (divs[this.index].offsetHeight)*this.index;
                }
            }
        }
            
        </script>
    </body>
</html>

猜你喜欢

转载自blog.csdn.net/zhanghl150426/article/details/82148980
今日推荐