当具有特定类的 div 靠近查看窗口顶部时,我花了很多时间尝试让动画正常工作。我有一些有效的东西,但它触发了类中 div 中的所有动画,而不仅仅是 View 中的动画。我认为 .each 会阻止这种情况发生?
$(function() {
var animated = $('.js-animate'),
distance = $(animated).offset().top,
$window = $(window);
replaceWithPaths(animated);
hideSVGPaths(animated);
$window.scroll(function() {
$(animated).each(function(i) {
if ( $window.scrollTop() >= distance-100 ) {
startSVGAnimation(this);
animated.splice(i,1);
}
});
});
});
我尝试过使用插件(inview、waypoints),但都不符合要求。有一个简单的解决方案吗?正如您可能已经了解到的那样,我刚刚开始掌握 JS/Jquery,所以如果您回答,请记住这一点。
最佳答案
这里的问题是这一行:
distance = $(animated).offset().top
作为documentation表示,offset() 返回第一个匹配元素的偏移量,而不是全部。
请改用此代码:
$(function() {
var animated = $('.js-animate'),
distance = $(animated).offset().top,
$window = $(window);
replaceWithPaths(animated);
hideSVGPaths(animated);
$window.scroll(function() {
$(animated).each(function(i) {
//$(this).offset().top gives you the current offset of the current element.
if ( $window.scrollTop() >= $(this).offset().top - 100 ) {
startSVGAnimation(this);
animated.splice(i,1);
}
});
});
});
或者,如果您确实想保存偏移量,以便在滚动时不必一遍又一遍地访问该属性,您可以像这样保存它们:
//Saves the distances to an array.
distance = animated.map(function() {
return $(this).offset().top;
}).get()
他们在 each
函数中访问它们,如下所示:
if ( $window.scrollTop() >= distance[i] - 100 ) {
//...
关于javascript - 当具有类的 div 进入 View 时触发函数 - 但不适用于具有该类的所有 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876648/