DIV CSS 佈局教程網

jQuery 實現指定 DIV 滾動到可見時觸發代碼
編輯:JQuery特效代碼     

在頁面中存在大量內容時,我們常常希望某個特定的 DIV 滾動進入視口時自動觸發一段代碼,例如改變某塊區域的樣式。本文分享一個實現該效果的完整示例:本頁在指定 DIV 出現時,將原本紅色的方塊改為藍色。

效果演示:https://hovertree.com/texiao/jquery/28/

效果二:https://hovertree.com/texiao/jquery/28/1.htm

既可以通過鼠標滾動,也可以使用鍵盤方向鍵操作。參考原文:https://hovertree.com/h/bjaf/jqguding.htm

實現思路

核心在於監聽窗口的 scroll 事件,判斷目標 DIV 距頂部的位置與當前滾動距離的關係。當滾動距離超過目標位置時,利用一個標志變量確保觸發的代碼只執行一次。

完整代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery 指定 DIV 滾動到出現時執行代碼 - 何問起</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script>
<style>
body { margin: 0px; font-family: Arial; }
a { color: blue; }
</style>
</head>
<body>
<div style="text-align:center;width:100%;margin:0px auto;">
<h1>何問起</h1>
指定 DIV 滾動到出現時,執行代碼。<br />
本頁為把紅色顏色改為藍色。<br />
請滾動頁面...<br />
<a href="https://hovertree.com/texiao/yestop/">Yestop</a>
<a href="https://hovertree.com">首頁</a>
<a href="https://hovertree.com/texiao/">特效</a>
</div>
<div style="height: 360px;background-color: #66FF66;text-align:center;"></div>
<div id="bg1" style="width:100%;text-align:center;height:200px;background-color:red"></div>
<div style="width:100%;text-align:center;height:300px;background-color:silver"></div>
<div style="width:100%;text-align:center;height:200px;background-color:skyblue" id="divhovertree">
何問起 &copy; hovertree.com<br />
本 DIV 出現時執行代碼,把紅色 div 改為藍色。
</div>
<div style="height: 800px;background-color:white"></div>
<script type="text/javascript">
/*
* 滾動條滑動,位置不變的 DIV 層
* div_id:DIV 的 ID 屬性值,必填參數
* offsetTop:滾動條滑動時 DIV 層距頂部的高度,可選參數
*/
function HoverTreeScroll(div_id) {
    var Obj = $('#' + div_id);
    // 判斷元素是否存在
    if (Obj.length != 1) { return false; }

    var offsetTop = arguments[1] ? arguments[1] : 0;
    var ObjTop = Obj.offset().top - $(window).height();
    var h_one = true;

    $(window).scroll(function () {
        if ($(window).scrollTop() > ObjTop) {
            if (h_one) {
                // 在這裡寫滾動到指定 DIV 時執行的代碼
                $("#bg1").css("background-color", "blue");
                h_one = false;
            }
        }
    });
}
// 已經滾動到這個 ID 為 divhovertree 的 DIV
HoverTreeScroll('divhovertree');
</script>
</body>
</html>

通過這個示例可以看到,只要合理利用 scroll 事件與位置判斷,就能實現豐富的滾動觸發交互效果,例如延遲加載、動畫展示或樣式切換等。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved