gpt4 book ai didi

javascript - 为网站滚动添加效果

转载 作者:行者123 更新时间:2023-11-28 02:57:00 25 4
gpt4 key购买 nike

我正在使用箭头键滚动网站内容。我想为此添加滚动计时和滚动效果。

我知道有很多库使用 jquery 来做这件事。我想要 javascript 中的解决方案。请帮忙。

var handler = function(e) {
e = e || window.event;
var k = e.keyCode || e.which;
switch (k) {
case 38:
document.body.scrollTop -= 1000;
document.documentElement.scrollTop -= 1000;
break;
case 40:
document.body.scrollTop += 1000;
document.documentElement.scrollTop += 1000;
break;
default:
return true;
}
if (e.preventDefault) e.preventDefault();
return false;
};
if (window.attachEvent) window.addEvent("onkeydown", handler, false);
else window.addEventListener("keydown", handler, false);
div {
height: 1000px;
width: 100%;
}
.red {
background: red;
}
.green {
background: green;
}
.yellow {
background: yellow;
}
<div class="red"></div>
<div class="green"></div>
<div class="yellow"></div>

最佳答案

是这样的吗?这不是最终产品,但绝对是这样。

此答案基于 another answer

var handler = function(e) {
e = e || window.event;
var k = e.keyCode || e.which;
switch (k) {
case 38:
//document.body.scrollTop -= 1000;
//document.documentElement.scrollTop -= 1000;
scrollBy(document.body.scrollTop - 1000, 500);
break;
case 40:
//document.body.scrollTop += 1000;
//document.documentElement.scrollTop += 1000;
scrollBy(document.body.scrollTop + 1000, 500);
break;
default:
return true;
}
if (e.preventDefault) e.preventDefault();
return false;
};
if (window.attachEvent) window.addEvent("onkeydown", handler, false);
else window.addEventListener("keydown", handler, false);

function scrollBy(to, duration) {
if (duration <= 0) return;
var difference = to - document.body.scrollTop;
var perTick = difference / duration * 10;

setTimeout(function() {
document.body.scrollTop = document.body.scrollTop + perTick;
if (document.body.scrollTop == to) return;
scrollBy(to, duration - 10);
}, 10);
}
div {
height: 1000px;
width: 100%;
}
.red {
background: red;
}
.green {
background: green;
}
.yellow {
background: yellow;
}
<div class="red"></div>
<div class="green"></div>
<div class="yellow"></div>

http://jsbin.com/goqadek/edit?html,css,js

关于javascript - 为网站滚动添加效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36615422/

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