我想要一种效果,如果向下滚动,您可以“平滑滚动”到下一个/上一个div
,具体取决于您是向上还是向下滚动。所以我有几个div的
<body>
<div class="wrapper">
<div class="slide">...</div>
<div class="slide">...</div>
<div class="slide">...</div>
<div class="slide">...</div>
<div class="slide">...</div>
<div class="slide">...</div>
</div>
</body>
所有这些都有100%的高度(“全屏”)。
我有一个尝试的JQuery函数,但是失败了:
var currentSlide = 0;
$(function()
{
var $prom = $('div.slide');
$(window).bind('mousewheel', function(event)
{
if(event.originalEvent.wheelDelta >= 0)
{
if(currentSlide === 0)
return;
--currentSlide;
}
else
{
if(currentSlide >= $prom.length)
return;
++currentSlide;
}
var target = $('div.slide')[currentSlide];
console.log(target);
$('html, body').animate({
scrollTop: target; //.offset().top
}, 1000);
});
});
如果我取消注释上面的代码并连接target.offset().top
它会给我带来错误,但如果我这样尝试,它总会将我滚动到第一个/顶部div。
我该如何解决这个问题?有更好的解决方案吗?
答案 0 :(得分:1)
非常感谢@Abhisek Malakar和@Gene R!他对我很有帮助!我会留下这个问题让他们被接受。
然而,我会展示我做了什么来扩展这个,因为即使在修复之后我遇到了一个问题,如果你滚动你的鼠标轮足够坚硬(这也修复了笔记本电脑的触摸板)它会继续滚动,我改进了方式如果您使用其他滚动方式(拖动滚动条/箭头/等),页面会识别您当前所在的div。任何改进建议都非常受欢迎!
再次,非常感谢!
var currentSlide = 0,
scrollSmooth = 1000,
$prom = $('div.slide');
$(function()
{
//Adding a binding listener to mousewheel (DOMMouseScroll is for FF)..
$(window).bind('mousewheel DOMMouseScroll', function(event)
{
//Firefox nema argument wheelDelta, ali ima detail
var delta = (event.originalEvent.wheelDelta !== undefined ?
event.originalEvent.wheelDelta : -event.originalEvent.detail);
if(delta >= 0)
{
if(currentSlide === 0)
return;
currentSlide--;
}
else
{
if(currentSlide >= $prom.length - 1)
return;
currentSlide++;
}
//Turning off scroll functionality untill div is reached
disableScroll();
setTimeout(function()
{
if (window.removeEventListener)
window.removeEventListener('DOMMouseScroll', preventDefault, false);
window.onmousewheel = document.onmousewheel = null;
window.onwheel = null;
window.ontouchmove = null;
document.onkeydown = null;
}, scrollSmooth);
var target = $prom[currentSlide];
$('html, body').animate({
scrollTop: $(target).offset().top
}, scrollSmooth);
});
});
//In case of different kinds of scrolling (arrows/scrollbar...) browser listens
//and changes currentSlide value based on where the scroll currently is.
$(window).scroll(function()
{
var screenSize = window.innerHeight;
var scrollSize = $(document).scrollTop();
for(var i = 0, temp = $prom.length; i < temp; i++)
{
if(scrollSize >= screenSize * i)
{
currentSlide = i;
}
}
});
//Universal method for preventing default behavious
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function disableScroll() {
if (window.addEventListener) // firefox
window.addEventListener('DOMMouseScroll', preventDefault, false);
window.onwheel = preventDefault; // chrome/MS edge/safari...
window.onmousewheel = document.onmousewheel = preventDefault; // older browsers
}