我有一个页面,上面有 5 个面板。当每个面板进入 View 时,我希望它的 2 个子元素根据用户滚动量减小大小。
我编写了一个函数,可以稍微缩小 DIV,但它发生在所有 DIV 上,而不是在每个元素进入 View 时发生,这有意义吗?
https://jsfiddle.net/n7vmaz9s/
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
if (scrollTop < 200) {
newWidth = 15;
} else if (scrollTop > 400) {
newWidth = 7.5;
} else {
newWidth = 15 - 7.5 * ((scrollTop - 200)) / 200;
}
$('.before').css({
'width': newWidth + "%"
});
$('.after').css({
'width': newWidth + "%"
});
})
当元素父级进入 View 时,如何让每个“之前”和“之后”div 工作?
我也尝试过使用 .each 这样...
$(window).scroll(function () {
$(".service-image").each(function(){
elementOffset = $(this).offset().top
var scrollTop = $(window).scrollTop();
elemDist = elementOffset - scrollTop;
console.log(elementOffset - scrollTop);
if (elemDist < 0) {
newWidth = 15;
} else if (elemDist > 400) {
newWidth = 7.5;
} else {
newWidth = 15 - 7.5 * ((scrollTop - 200)) / 200;
}
$('.before').css({
'width': newWidth + "%"
});
$('.after').css({
'width': newWidth + "%"
});
});
})
最佳答案
不确定我是否完全理解所需的效果。但我写了一个 fiddle ,模仿每个面板的动画方式,但对于单个面板“在 View 中”时:https://jsfiddle.net/zd0p8jfu/
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
$(".service-image").each(function(){
var relativeScroll = scrollTop - $(this).offset().top;
if (scrollTop < $(this).offset().top + 200) {
newWidth = 15;
} else if (scrollTop > $(this).offset().top + 400) {
newWidth = 7.5;
} else {
newWidth = 15 - 7.5 * ((relativeScroll - 200)) / 200;
}
$(this).find('.before').css({
'width': newWidth + "%"
});
$(this).find('.after').css({
'width': newWidth + "%"
});
});
});
要反转方向,您只需交换数学,如下所示:
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
$(".service-image").each(function(){
var relativeScroll = scrollTop - $(this).offset().top;
if (scrollTop < $(this).offset().top + 200) {
newWidth = 7.5;
} else if (scrollTop > $(this).offset().top + 400) {
newWidth = 15;
} else {
newWidth = 7.5 * ((relativeScroll - 200) / 200) + 7.5;
}
$(this).find('.before').css({
'width': newWidth + "%"
});
$(this).find('.after').css({
'width': newWidth + "%"
});
});
});
关于javascript - 对每个元素运行函数一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42496972/