javascript 没有 jQuery 的平滑滚动锚链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17733076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Smooth scroll anchor links WITHOUT jQuery
提问by drozdzynski
Is it possible to use smooth scroll to anchor links but withoutjQuery
? I am creating a new site and I don't want to use jQuery
.
是否可以使用平滑滚动来锚定链接但没有jQuery
?我正在创建一个新站点,但不想使用jQuery
.
采纳答案by Ian
Using the function from here: JavaScript animationand modifying it to modify a property (not only a style's property), you can try something like this:
使用此处的函数:JavaScript animation并修改它以修改属性(不仅仅是样式的属性),您可以尝试以下操作:
function animate(elem, style, unit, from, to, time, prop) {
if (!elem) {
return;
}
var start = new Date().getTime(),
timer = setInterval(function () {
var step = Math.min(1, (new Date().getTime() - start) / time);
if (prop) {
elem[style] = (from + step * (to - from))+unit;
} else {
elem.style[style] = (from + step * (to - from))+unit;
}
if (step === 1) {
clearInterval(timer);
}
}, 25);
if (prop) {
elem[style] = from+unit;
} else {
elem.style[style] = from+unit;
}
}
window.onload = function () {
var target = document.getElementById("div5");
animate(document.scrollingElement || document.documentElement, "scrollTop", "", 0, target.offsetTop, 2000, true);
};
DEMO:https://jsfiddle.net/zpu16nen/
演示:https : //jsfiddle.net/zpu16nen/
Make sure you size the window small enough so there's actually a scrollbar and can scroll to the 5th div.
确保窗口的大小足够小,以便实际上有一个滚动条并且可以滚动到第 5 个 div。
And no, it didn't require the recreation of 25% of jQuery.
不,它不需要重新创建 25% 的 jQuery。
This would obviously needly highly modified depending on what your question actually means (like when the window hash changes, or something like that).
这显然需要高度修改,具体取决于您的问题的实际含义(例如窗口哈希更改时或类似情况)。
Note that with jQuery, it's as easy as:
请注意,使用 jQuery,它就像:
$(document).ready(function () {
$("html, body").animate({
scrollTop: $("#div5").offset().top
}, 2000);
});
DEMO:http://jsfiddle.net/7TAa2/1/
演示:http : //jsfiddle.net/7TAa2/1/
Just saying...
就是说...
回答by Tejas Shah
Extending this answer: https://stackoverflow.com/a/8918062/3851798
扩展这个答案:https: //stackoverflow.com/a/8918062/3851798
After defining your function of scrollTo, you can pass the element you want to scrollTo in the function.
定义好你的scrollTo 函数后,你可以在函数中传递你想要scrollTo 的元素。
function scrollTo(element, to, duration) {
if (duration <= 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
setTimeout(function() {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop === to) return;
scrollTo(element, to, duration - 10);
}, 10);
}
If you have a div with an id="footer"
如果你有一个 id="footer" 的 div
<div id="footer" class="categories">…</div>
In the script that you run to scroll you can run this,
在您运行滚动的脚本中,您可以运行它,
elmnt = document.getElementById("footer");
scrollTo(document.body, elmnt.offsetTop, 600);
And there you have it. Smooth scrolling without jQuery. You can actually play around with that code on your browser's console and fine tune it to your liking.
你有它。没有 jQuery 的平滑滚动。您实际上可以在浏览器的控制台上使用该代码并根据自己的喜好对其进行微调。
回答by Alexander Svetly
Actually, there is more lightweight and simple way to do that: https://codepen.io/ugg0t/pen/mqBBBY
实际上,有更轻量级和简单的方法来做到这一点:https: //codepen.io/ugg0t/pen/mqBBBY
function scrollTo(element) {
window.scroll({
behavior: 'smooth',
left: 0,
top: element.offsetTop
});
}
document.getElementById("button").addEventListener('click', () => {
scrollTo(document.getElementById("8"));
});
div {
width: 100%;
height: 200px;
background-color: black;
}
div:nth-child(odd) {
background-color: white;
}
button {
position: absolute;
left: 10px;
top: 10px;
}
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
<div id="7"></div>
<div id="8"></div>
<div id="9"></div>
<div id="10"></div>
<button id="button">Button</button>
回答by Anderpo
Use this:
用这个:
let element = document.getElementById("box");
element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({block: "end"});
element.scrollIntoView({behavior: "instant", block: "end", inline: "nearest"});
回答by Louis Maddox
CSS3 transitions with a :target
selector can give a nice result without any JS hacking. I was just contemplating whether to imlement this but without Jquery it does get a bit messy. See this questionfor details.
带有:target
选择器的CSS3 转换可以在没有任何 JS hack 的情况下提供不错的结果。我只是在考虑是否要实现这一点,但没有 Jquery,它确实有点混乱。有关详细信息,请参阅此问题。
回答by illvart
Smooth Scroll behavior with polyfill...
使用 polyfill 平滑滚动行为...
Example:
例子:
document.querySelectorAll('a[href^="#"]').addEventListener("click", function(event) {
event.preventDefault();
document.querySelector(this.getAttribute("href")).scrollIntoView({ behavior: "smooth" });
});
Repository: https://github.com/iamdustan/smoothscroll
回答by Oleksandr Kozlov
Vanilla js variant using requestAnimationFrame
with easings and all browsers supported:
使用requestAnimationFrame
缓动和所有浏览器支持的Vanilla js 变体:
const requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
function scrollTo(to) {
const start = window.scrollY || window.pageYOffset
const time = Date.now()
const duration = Math.abs(start - to) / 3;
(function step() {
var dx = Math.min(1, (Date.now() - time) / duration)
var pos = start + (to - start) * easeOutQuart(dx)
window.scrollTo(0, pos)
if (dx < 1) {
requestAnimationFrame(step)
}
})()
}
Any easingsupported!
支持任何缓动!
回答by Alberto Junior
Try this code here:
在这里试试这个代码:
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth'
});
回答by Fran?ois PIQUARD
For anyone in 2019, first, you add an event listener
对于 2019 年的任何人,首先,您添加一个事件侦听器
document.getElementById('id').addEventListener('click', () => scrollTo())
then you target the element and go smoothly to it
然后你瞄准这个元素并顺利地找到它
function scrollTo() {
let target = document.getElementById('target');
target.scrollIntoView({
behavior: "smooth",
block: "end",
inline: "nearest"
})
}
回答by Alexandre Aimbiré
This is a pretty old question, but I think it's important to say that nowadays smooth scrolling is supported in CSS, so there's no need for any scripts:
这是一个很老的问题,但我认为重要的是现在 CSS 支持平滑滚动,因此不需要任何脚本:
html {
scroll-behavior: smooth;
}
This property still has no support for Safari or IE/Edge as of 2019, so for a full crossbrowser support, you'll still have to use a script.
截至 2019 年,此属性仍然不支持 Safari 或 IE/Edge,因此要获得完整的跨浏览器支持,您仍然必须使用脚本。