我想在元素滚动到 View 中时将 .animated
类添加到该元素。
到目前为止,我有以下代码:
function isElementInViewport(elem) {
var $elem = $(elem);
// Get the scroll position of the page.
var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
var viewportTop = $(scrollElem).scrollTop();
var viewportBottom = viewportTop + $(window).height();
// Get the position of the element on the page.
var elemTop = Math.round( $elem.offset().top );
var elemBottom = elemTop + $elem.height();
return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}
// Check if it's time to start the animation.
function checkAnimation() {
var $elem = $('.circle-purple-lighter');
// If the animation has already been started
if ($elem.hasClass('animated')) return;
if (isElementInViewport($elem)) {
// Start the animation
$elem.addClass('animated');
}
}
但是,这仅适用于 Chrome。关于如何修复(或其他方法)跨浏览器的任何想法? IE9+
最佳答案
这可能会有所帮助:
jQuery 可见插件: https://github.com/teamdf/jquery-visible
这里是如何使用这个插件的演示(我在 Chrome 和 Firefox 中测试过):
JSFiddle
$(function () {
var $h1 = $('h1');
var testVis = function () {
$h1.each(function () {
if ($(this).visible()) {
$(this).addClass('animated');
} else {
$(this).removeClass('animated');
}
});
};
$(window).on('scroll resize', testVis);
testVis();
});
关于jquery - 如何在浏览器窗口中可见时添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20713265/