我希望在滚动到视图中时将类.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 +
答案 0 :(得分:2)
这可能有所帮助:
jQuery可见插件: https://github.com/teamdf/jquery-visible
以下是如何使用此插件的演示(我在Chrome和Firefox中测试过):
$(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();
});