我有一个脚本,在页面向下滚动时向元素添加一个类。我如何添加其他变量,以便在将各个元素放入视图时将其添加到各个元素中?
这是原作:
// Returns true if the specified element has been scrolled into the viewport.
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 = $('.flip-card');
// If the animation has already been started
if ($elem.hasClass('start')) return;
if (isElementInViewport($elem)) {
// Start the animation
$elem.addClass('start');
}
}
// Capture scroll events
$(window).scroll(function(){
checkAnimation();
});
这是我更新的脚本 - 这不起作用:
// Returns true if the specified element has been scrolled into the viewport.
function isElementInViewport(elem) {
var $elem = $(elem);
var $elem2 = $(elem2);
// 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();
var elem2Top = Math.round( $elem2.offset().top );
var elem2Bottom = elemTop + $elem2.height();
return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
return ((elem2Top < viewportBottom) && (elem2Bottom > viewportTop));
}
// Check if it's time to start the animation.
function checkAnimation() {
var $elem = $('.flip-card');
var $elem2 = $('.flip-card-1');
// If the animation has already been started
if ($elem.hasClass('start')) return;
if (isElementInViewport($elem)) {
// Start the animation
$elem.addClass('start');
}
if ($elem2.hasClass('start')) return;
if (isElementInViewport($elem2)) {
// Start the animation
$elem2.addClass('start');
}
}
// Capture scroll events
$(window).scroll(function(){
checkAnimation();
});
我想我是以错误的方式解决这个问题的?
答案 0 :(得分:0)
你必须改变你的checkAnimation功能:
function checkAnimation() {
var $elements = [$('.flip-card'), $('.flip-card-1')];
$elements.forEach(function(element) {
// If the animation has already been started
if (element.hasClass('start')) return;
if (isElementInViewport(element)) {
// Start the animation
element.addClass('start');
}
}
}
只需将要检查的所有元素放入数组中即可。然后你可以检查那个数组中的所有元素。这样你就不需要两个方法中的第二个元素了。