gpt4 book ai didi

javascript - 用鼠标滚动到 block 的高度

转载 作者:行者123 更新时间:2023-11-30 12:04:06 25 4
gpt4 key购买 nike

滚动页面滚动恰好发生在其中 block 的高度(里面的代码)怎么办?

我不想使用该库,因为很可能需要添加 2-5 行代码来解决在 block 的高度(预定像素数)滚动时滚动页面的问题。

第二个问题是如何让这个流畅的滚动,不是那种刚从一个单位切换到另一个单位的感觉。

function slide() {
h = document.documentElement.clientHeight
$(".one, .two, .three").css('height', h);
};

$(window).resize(slide);
$(document).ready(slide);
.one,
.two,
.two {
display: block;
position: relative;
width: 100%;
}
.one {
background: #CD5;
}
.two {
background: aquamarine;
}
.three {
background: #2196F3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>

最佳答案

将滚动处理程序绑定(bind)到 mousewheel 和 DOMMouseScroll 事件,并使用 (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) 确定滚动的方向。然后使用 $().offset().top 找到要滚动的 div 的顶部,并使用 $.animate() 进行滚动。

function slide() {
h = document.documentElement.clientHeight
$(".one, .two, .three").css('height', h);
};
$(window).resize(slide);
$(document).ready(slide);


$(document).bind('mousewheel DOMMouseScroll', function(event) {
scroll(event);
});

var num = 1;
var scrolling = false;

function scroll(event) {
event.preventDefault();
if (!scrolling) {
scrolling = true;
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
num--;
num = num < 1 ? 1 : num;
} else {
num++;
num = num > 3 ? 3 : num;
}

$('html, body').animate({
scrollTop: $(".num" + num).offset().top
}, 500, "linear", function() {
scrolling = false;
});
}
}
.one,
.two,
.two {
display: block;
position: relative;
width: 100%;
}
.one {
background: #CD5;
}
.two {
background: aquamarine;
}
.three {
background: #2196F3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="one num1"></div>
<div class="two num2"></div>
<div class="three num3"></div>

关于javascript - 用鼠标滚动到 block 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35764232/

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