在处理一个更大的项目时,我制作了一个装有不同内容的盒子。
框的宽度为 1000 像素,显示 5 张(共 50 张)图片。框页面从前 5 个切换到下 5 个,依此类推每 8 秒一次(已经用 jQuery 动画编写了这个)。
现在我的问题是,盒子位于我页面的中间,所以当访问者停留在顶部并在大约 30 秒后向下滚动时,他们会错过我盒子中的第一张图片。
所以我的计划是在访问者可以看到框(视口(viewport))的那一刻开始我的框的分页。
我为此做了一个测试页
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box">THIS BOX<br>THIS BOX<br>THIS BOX</div>
<div class="box"></div>
<div class="box"></div>
.box {
border:2px solid black;
height: 400px;
width: 200px;
margin: 0 auto;
margin-top:10px;
}
到目前为止我正在使用
jQuery(document).ready(function(){
getThemenCount();
moveThemenAnimate();
});
我的计划是从文档准备好切换到if element is in viewport
之类的东西
我很容易尝试找到不同的方法,但我似乎无法让它工作。
http://jsfiddle.net/moagrius/wN7ah/
仅适用于不同的类和点击。
我想做的(也是我不能做的)是我想在盒子进入访问者 window 的那一刻开始我的动画脚本。这样他就可以从图片 1 开始在框中看到我的图片。
有没有可能让它像我计划的那样工作?不知何故,我无法找到如何设置 jQuery 表达式 + 脚本,仅当我使用类和点击时(如上面的 fiddle )
最佳答案
您需要监听 window
scroll
事件,并触发回调以检查框是否在视口(viewport)中。
从性能方面来看,监听 scroll
事件可能是危险的,因为回调自然会在用户滚动时触发。使用节流机制限制触发回调的次数被认为是最佳实践。
此工作示例每秒检查用户滚动位置 4 次,并在框出现在 View 中后禁用事件监听器。
// document ready
$(function () {
// define the isOnScreen plugin from http://jsfiddle.net/moagrius/wN7ah/
$.fn.isOnScreen = function() {
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft(),
right: win.scrollLeft() + win.width(),
bottom: win.scrollTop() + win.height()
};
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
// define throttling function for use in scroll event listener
// ref: http://blogorama.nerdworks.in/javascriptfunctionthrottlingan/
function throttle(delay, callback) {
var previousCall = new Date().getTime();
return function() {
var time = new Date().getTime();
if ((time - previousCall) >= delay) {
previousCall = time;
callback.apply(null, arguments);
}
};
}
// set up an event to listen for window scroll 4 times a second
$(window).on('scroll', throttle( 250, function () {
// if #the-box is visible the call init functions and disable window scroll
// event listener, as you only want to initialise the lightbox once
if ( $("#the-box").isOnScreen() ) {
// for demo purposes
alert('init');
// call your init functions here
//getThemenCount();
//moveThemenAnimate();
// turn off scroll listener
$(window).off('scroll');
}
}));
});
关于javascript - 视口(viewport) JQuery - 如果元素在视口(viewport)中,则将文档准备好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24803195/