gpt4 book ai didi

javascript - 滚动到浏览器中已有的下一个 div

转载 作者:行者123 更新时间:2023-11-28 08:02:54 24 4
gpt4 key购买 nike

我有一系列 100% 高度的 div,具有滚动功能,可以在背景单击时将您带到视口(viewport)之外的下一个 div。但是,如果下一个 div 已经稍微位于视口(viewport)中,则整个内容将被视为可见,并且滚动将绕过它。任何人都可以提供有关如何让脚本滚动到 div 的指导,即使它已经部分位于视口(viewport)中?

Codepen here.

如果您开始在 codepen 中稍微滚动,然后单击背景,您会发现它不会滚动到视口(viewport)中已有的 div,而是滚动到之后的 div。

$(document).ready(function() {


// get initial nav height
var $window = $(window);
var wst = $window.scrollTop();
var th = $('div.top').height();
var currentSlide = $('#wrapper').data( 'current-slide', $('div.slide').eq(0) );

$('div.scroll_images').css({ height: 'auto', overflow: 'visible', top: 0 });
$('div.scroll_images div.inner').css({ position: 'absolute', top: 0 });
$('div.slide').each(function() {
$(this).css('padding',function() {
return (($(window).height()-$(this).height())/2)+'px 0'
});
});



// scrollto for click on slide
jQuery.fn.scrollTo = function(hash) {
$this = $(this);
st = $this.offset().top - th; // subtract nav height
$('html, body').animate({ scrollTop: st }, 550
);
}

$('#wrapper').click(function(e){
//get the current slide index from the body tag.
$this = currentSlide.data( 'current-slide' );
$next = $(".slide:below-the-fold");

if($next.length) {
$next.scrollTo($next.attr('id'));
//Save the next slide as the current.
$('#wrapper').data( 'current-slide', $next );
} else {
//Throw us back to the top.
$('div.slide:first').scrollTo($('div.slide:first').attr('id'));
//Save the first slide as the first slide, which
//Cycles us back to the top.
$('#wrapper').data( 'current-slide', $('div.slide:first'));
}
})
//Images fade in
$('img').hide();
$('img').each(function(i) {
if (this.complete) {
$(this).fadeIn();
} else {
$(this).load(function() {
$(this).fadeIn();
});
}
});

//Stop links affecting scroll function
$("a").click(function(e) {
e.stopPropagation();
});

});




(function($) {

$.belowthefold = function(element, settings) {
var fold = $(window).height() + $(window).scrollTop();
return fold <= $(element).offset().top - settings.threshold;
};


$.extend($.expr[':'], {
"below-the-fold": function(a, i, m) {
return $.belowthefold(a, {threshold : 0});
}
});

})(jQuery);

最佳答案

这就是我可能尝试做的事情:浏览该系列中的每个 div。找到 offset() 最接近 $(window).scrollTop() 的 div。现在,找到“当前”div 后面的 next() div 并滚动到它。

要比较每个 div 的 offset(),请尝试如下操作:

var closest = $('[selector]:first');
$('[selector]').each(function() {
var oldDistance = Math.abs(closest.offset() - $(window).scrollTop());
var newDistance = Math.abs($(this).offset() - $(window).scrollTop());

if(newDistance < oldDistance) {
closest = $(this);
}
}

关于javascript - 滚动到浏览器中已有的下一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25164330/

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