jquery - 如何在浏览器窗口中可见时添加类

标签 jquery

我想在元素滚动到 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/

相关文章:

jquery - 为什么框阴影只有在滚动后才可见?

jquery - 如何同时查找数组中的两个值?

javascript - jQuery 自动完成返回整个数组而不是搜索值

javascript - jQuery 添加自定义密码规则不起作用

javascript - 修复底部 div 到达另一个 div 后停止的问题

javascript - myAudio.play() 不是一个函数

javascript - jquery 事件不适用于 mozilla 并适用于其他浏览器

jquery - onHover 事件未在 Chart.js 中触发

javascript - jquery 焦点回到相同的输入字段,错误不适用于所有浏览器

javascript - jQuery slideToggle() 实现的故障