Jquery-在视口中选择具有类名的图像
我有一个带有图片的网页。当我滚动到图像时,我希望它们具有动画效果。我就是这样做的Jquery-在视口中选择具有类名的图像,jquery,html,scroll,Jquery,Html,Scroll,我有一个带有图片的网页。当我滚动到图像时,我希望它们具有动画效果。我就是这样做的 $.fn.is_on_screen = function(){ var win = $(window); var viewport = { top : win.scrollTop(), left : win.scrollLeft() }; viewport.right = viewport.left + win.width(); viewpor
$.fn.is_on_screen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + 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));
};
$(window).scroll(function(){
if( $('.effect').is_on_screen()){
$('.effect').addClass('animated bounceIn');
}
});
您可以尝试以下方法。首先,将选定图元添加到列表中并保持其当前可见性
var settings = {
throttle: 300
};
var elements = [];
$.fn.viewport = function (options) {
$.extend(settings, options);
elements = this;
return elements.each(function () {
$(this).data('visible', $(this).visible());
});
};
要检查元素在视口中是否可见,可以使用getBoundingClientRect
方法返回元素相对于视口的坐标
$.fn.visible = function () {
var rect = this[0].getBoundingClientRect();
var $window = $(window);
return (
rect.top <= $window.height()
&& rect.right >= 0
&& rect.bottom >= 0
&& rect.left <= $window.width()
);
};
用法示例:
$('div').viewport().on({
enter: function () {
$(this).addClass('visible');
},
leave: function () {
$(this).removeClass('visible');
}
});
请参阅此处的实时示例:。至少使用一个循环!非常感谢@Cătălin Dogaru。你解决了我的问题。
var timer;
$(window).on('scroll', function (event) {
if (!timer) {
timer = setTimeout(function () {
$.each(elements, function () {
var visible = $(this).visible();
if (visible) {
if (!$(this).data('visible')) {
$(this).data('visible', visible);
$(this).trigger('enter', event);
}
} else if ($(this).data('visible')) {
$(this).data('visible', visible);
$(this).trigger('leave', event);
}
});
timer = null;
}, settings.throttle);
}
});
$('div').viewport().on({
enter: function () {
$(this).addClass('visible');
},
leave: function () {
$(this).removeClass('visible');
}
});