2013-12-16 184 views
0

我想在用户滚动页面时为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; 
      }); 

     } 
    } 
}); 

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

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

我的意思是:如果该元素是在页面加载可见,动画将自动开始......如果元素是不是在页面加载可见,动画等待滚动到达元素开始...

谢谢。

回答

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。 在提供的链接中有使用指南和更多信息。 祝你好运!