JS監聽滾動條進度


HTML部分:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div>
    <h2>scroll</h2>
    <div id="nav">
        <div class="f1">floor1</div>
        <div class="f2">floor2</div>
        <div class="f3">floor3</div>
        <div class="f4">floor4</div>
        <div class="f5">floor5</div>
    </div>
    <p>
        頁面結構
    </p>
    <div class="main">
        <div id="f1">測試1</div>
        <div id="f2">測試2</div>
        <div id="f3">測試3</div>
        <div id="f4">測試4</div>
        <div id="f5">測試5</div>
    </div>
</div>
</body>
</html>

 

CSS部分:

    <style>
        .main div {
            height: 970px;
            width: 300px;
            margin: 20px;
            background-color: #C0C0C0;
        }

        #nav {
            position: fixed;
            width: 100px;
            height: 200px;
            top: 40%;
            right: 10px;
        }

        #nav div {
            cursor: pointer;
            text-align: center;
        }
    </style>

 

JS部分:

<script>
    $(function () {
        $(window).scroll(function () {//為頁面添加頁面滾動監聽事件
            var wst = $(window).scrollTop(); //滾動條距離頂端值
            for (var i = 1; i < 6; i++) {             //加循環
                if ($("#f" + i).offset().top <= wst + 10) { //判斷滾動條位置
                    $('#nav div').css("background-color", "white");
                    $(".f" + i).css("background-color", "red");
                }
            }
        });
        $('#nav div').click(function () {
            $('html').animate({scrollTop: $("#" + this.className).offset().top}, 500);
            // $("#" + this.className)[0].scrollIntoView(true);//h5 scrollIntoView()

        });
    });
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM