滚动上的动画元素

时间:2013-12-16 18:32:40

标签: javascript jquery animation

我想在用户滚动页面时为div设置动画。

为此,我实现了这段代码:

var slide = jQuery(".apresentacao-spc-01");
var opening = false;
var closing = false;
var pos = jQuery(window).scrollTop();
jQuery(window).scroll(function() {
    var pos = jQuery(window).scrollTop();
    console.log(pos);
    if (pos > 100) {

        if (!opening) {

            opening = true; closing = false;
            slide.stop().animate({
                'opacity': 1,
                'margin-left': '0px'
            }, 700, function() {
                opening = false;
            });

        }


    } else {
        if (!closing) {
            closing = true; opening = false;
            slide.stop().animate({
                'opacity': 0,
                'margin-left': '-1000px'
            }, 500, function() {
                closing = false;
            });

        }
    }
});

问题是: 使用“if(pos> 100){”,如果用户分辨率大到足以在需要滚动之前显示该元素,除非他开始滚动页面,否则他将看不到该元素。

我的问题是: 如何获得元素可见时将执行的滚动动画?

我的意思是:如果元素在页面加载时可见,动画会自动启动...如果元素在页面加载时不可见,则动画会等待滚动到达要启动的元素...

感谢。

1 个答案:

答案 0 :(得分:0)

你可以做一些不同的事情。我的第一个想法是用这样的东西来查询视口的高度:

var viewportWidth  = document.documentElement.clientWidth
, viewportHeight = document.documentElement.clientHeight

如果动画高于元素向下的距离,则触发动画。

一个更动态的解决方案是使用一个函数来检查元素是否自动处于视口中,这样你就不必担心如果你改变页面上的内容就调整高度:

function isElementInViewport (el) {
var rect = el.getBoundingClientRect();

return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
    rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}

归功于this response。 提供的链接中有使用指南和更多信息。 祝你好运!

相关问题