元素在视口中时的jquery触发器函数

时间:2011-05-06 12:04:09

标签: jquery function triggers viewport

当jquery.localscroll到达文档的某个点时,我想触发一个事件,一个div。

让我们说我们从顶部div垂直滚动到第三个。当它到达那里时,动作就会触发。

4 个答案:

答案 0 :(得分:43)

jQuery Waypoints插件http://imakewebthings.github.com/jquery-waypoints/应该可以做到这一点

更新

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery Waypoints Plugin - Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
    <script src="http://imakewebthings.github.com/jquery-waypoints/waypoints.min.js" type="text/javascript"></script>
    <style type="text/css">
        #mydiv {background-color:#FF0000; margin:1500px 0;}
    </style>
</head>
<body>

<div id="mydiv">
    Content goes here
</div>

<script type="text/javascript">
$(function() {
       $('#mydiv').waypoint(function() {
         window.location.href = 'http://google.com';
         }, {
           offset: '100%'
         });
    });
</script>
</body>
</html>

答案 1 :(得分:18)

您可能还希望看到以下微小的插件,它在过去帮助我,它非常干净:

示例用法:

$('div').bind('inview', monitor);
function monitor(event, visible)
{
    if(visible)
    {
      // element is now visible in the viewport
    }
    else
    {
      // element has gone out of the viewport
    }
}

答案 2 :(得分:6)

jQuery Bullseye:http://static.pixeltango.com/jQuery/Bullseye/在视口检测方面也做得很好!

答案 3 :(得分:4)

https://github.com/stutrek/scrollMonitor

var scrollMonitor = require("./scrollMonitor"); // if you're not using require, you can use the scrollMonitor global.
var myElement = document.getElementById("itemToWatch");

var elementWatcher = scrollMonitor.create( myElement );

elementWatcher.enterViewport(function() {
    console.log( 'I have entered the viewport' );
});
elementWatcher.exitViewport(function() {
    console.log( 'I have left the viewport' );
});

elementWatcher.isInViewport - true if any part of the element is visible, false if not.
elementWatcher.isFullyInViewport - true if the entire element is visible [1].
elementWatcher.isAboveViewport - true if any part of the element is above the viewport.
elementWatcher.isBelowViewport - true if any part of the element is below the viewport.