我已经阅读了几个与此相关的类似问题,但我无法让它发挥作用。我在 jQuery 中有一个滚动检测功能,我想要它有 3 个参数:
function scroll_detection(box_selector, trigger_offset, the_animation){
//something here
the_animation();
}
其中 the_animation 是一个将像这样调用的函数:
scroll_detection("section", .8, function(){
//stuff here
});
问题是,当我添加函数时,动画不再运行。
此代码完美运行:
function scroll_detection(duration, box_selector, element_selector, ease, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
$(this).find(element_selector).animate( { marginLeft: "0" }, duration, ease );
}
});
});
}
scroll_detection(2000, "section", ".section-title", "easeOutBack", .8);
scroll_detection(3000, ".article-wrap", ".article-title", "easeOutBounce", .7);
但这不是:
function scroll_detection(the_animation, box_selector, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
the_animation();
}
});
});
}
scroll_detection( function(){
$(this).find(".section-title").animate( { marginLeft: "0" }, 2000, "easeOutBounce");
}, "section", .8);
我希望能够轻松地改变我想要的效果。任何帮助将不胜感激。
编辑 11/09/2015:
正如@Aguardientico 和@LuiGui 所指出的,问题在于回调函数中 $(this) 的范围,我采用了@Aguardientico 解决方案。
jQuery(document).ready(function($){
function scroll_detection(the_animation, box_selector, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
the_animation.call(post); //Add call to give the function the right scope
}
});
});
}
scroll_detection( function(){
$(this).find(".section-title").animate( { marginLeft: "0" }, 2000, "easeOutBounce");
}, "section", .8);
最佳答案
这看起来像是与 scope
相关的问题,您正在匿名函数内调用 $(this)
又名 the_animation
,如果您请执行下列操作? the_animation.call(post)
function scroll_detection(the_animation, box_selector, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
the_animation.call(post);
}
});
});
}
scroll_detection( function(){
$(this).find(".section-title").animate( { marginLeft: "0" }, 2000, "easeOutBounce");
}, "section", .8);
关于javascript - jQuery 函数作为其他 jQuery 函数的参数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32534221/