gpt4 book ai didi

jquery - 当需要动态添加类时使用 Waypoints 的更好方法是什么?

转载 作者:行者123 更新时间:2023-12-01 04:03:39 28 4
gpt4 key购买 nike

当用户滚动时,我在元素上使用 Waypoints 和 Animate.css。它看起来和工作都很好,但是我的 JS 文件看起来很困惑,因为我还必须使用 JS 添加类,因为它们不能出现在这个项目的标记中。我对 jQuery 还很陌生,但我觉得必须有一种更好、更干的方式来完成我正在做的事情!

下面是我的脚本文件的一部分,用于添加类并与 Waypoint 类交互 - 由于动画的内容量很大,它变得非常长。任何为我指明正确方向的帮助将不胜感激!

(function($) {
$(function() {
$('.section-content').css('opacity', 0).waypoint(function() {
$('.section-content').addClass('delay animated fadeInUp');
}, {
offset: '100%'
});

$('.three-modules .module').css('opacity', 0).waypoint(function() {
$('.three-modules .module').addClass('delay animated fadeInUp');
}, {
offset: '75%'
});

$('.section-title').css('opacity', 0).waypoint(function() {
$('.section-title').addClass('delay animated fadeInUp');
}, {
offset: '75%'
});

$('.content-image-section').css('opacity', 0).waypoint(function() {
$('.content-image-section').addClass('delay animated fadeInLeft');
}, {
offset: '75%'
});
$('.quiz-image-container').css('opacity', 0).waypoint(function() {
$('.quiz-image-container').addClass('delay animated fadeInRight');
}, {
offset: '75%'
});

// …keeps going like this
});
})(jQuery);

最佳答案

如果您只是想减少上面代码中的重复,您可以将重复的代码粘贴在一个带有更改位参数的函数中,例如

function animateElementOffset(query, class, offset) {
$(query).css('opacity', 0).waypoint(function() {
$(query).addClass('delay animated ' + class);
}, {
offset: offset
});
}

(function($) {
$(function() {
animateElementOffset('.section-content', 'fadeInUp', '100%');
animateElementOffset('.three-modules .module', 'fadeInUp', '75%');
animateElementOffset('.section-title', 'fadeInUp', '75%');
animateElementOffset('.content-image-section', 'fadeInLeft', '75%');
animateElementOffset('.quiz-image-container', 'fadeInRight', '75%');
});
})(jQuery);

此外,如果您重复使用相同的元素,那么集中与每个元素匹配的查询可能是值得的,例如

function getAnimationHandle(query) {
var element = $(query);
return {
animateOffset: function (class, offset) {
element.css('opacity', 0).waypoint(function() {
$(query).addClass('delay animated ' + class);
}, {
offset: offset
});
}
}
}

(function($) {
$(function() {
var sectionContent = getAnimationHandle('.section-content');
var threeModulesModule = getAnimationHandle('.three-modules .module');
var sectionTitle = getAnimationHandle('.section-title');
var contentImageSection = getAnimationHandle('.content-image-section');
var quizImageContainer = getAnimationHandle('.quiz-image-container');

sectionContent.animateOffset('fadeInUp', '100%');
threeModulesModule.animateOffset('fadeInUp', '75%');
sectionTitle.animateOffset('fadeInUp', '75%');
contentImageSection.animateOffset('fadeInLeft', '75%');
quizImageContainer.animateOffset('fadeInRight', '75%');
});
})(jQuery);

关于jquery - 当需要动态添加类时使用 Waypoints 的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34593237/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com