这不是编码问题而是理解问题。我有以下代码,它执行它应该做的事情,即在滚动到它们时向svg元素添加和删除类。
$(document).ready(function(){
let allShapes = $("svg path, svg ellipse, svg polyline, svg line");
$(allShapes).each(function(){
let length = this.getTotalLength() + 5;
$(this).css({'stroke-dasharray': length, 'stroke-dashoffset': length});
});
let $window = $(window);
$window.on('scroll resize', check_if_in_view);
$window.trigger('scroll');
function check_if_in_view() {
let window_height = $window.height();
let window_top_position = $window.scrollTop();
let window_bottom_position = (window_top_position + window_height);
$.each(allShapes, function() {
let thisElement = $(this);
let element_height = thisElement.outerHeight();
let element_top_position = thisElement.offset().top + (window_height*0.2);
let element_bottom_position = (element_top_position + element_height);
if ((element_bottom_position >= window_top_position) &&
(element_top_position <= window_bottom_position)) {
thisElement.addClass('animate');
} else {
thisElement.removeClass('animate');
}
});
}
});
我的问题是关于 $ window.on('scroll resize',check_if_in_view); 部分。
为什么事件名称“check_if_in_view”在没有括号的情况下工作,即使它是一个函数?我会认为“check_if_in_view()”是写它的正确方法。正如你可能已经想到的那样,我有点frankenstein-ed这段代码,这是我打破它之前没有触及的现有部分:/
提前致谢!