javascript 滚动_用5行JavaScript平滑页面滚动

javascript 滚动

HTML has always had the ability to jump to locations on a page, provided the target element has an id attribute, via a technique known as anchor links.

只要目标元素具有id属性, HTML便可以通过锚链接跳转到页面上的位置。

However, this movement is instantaneous. For the sake of appearance, a site's design sometimes calls for a smooth or slowed scroll to a point on a page.

但是,该运动是瞬时的。 为了外观起见,网站的设计有时需要平滑或缓慢地滚动到页面上的某个点

Historically, this was achieved with JQuery, but it's overkill to load a framework just for one technique. Modern JavaScript provides a more efficient, native alternative, in the form of the window.scrollTo method.

从历史上看,这是通过JQuery实现的,但是仅为一种技术加载框架是过大的。 现代JavaScript以window.scrollTo方法的形式提供了一种更有效的本机替代方法。

A standard anchor link is used as the basis of the technique: that way, if the new smooth scroll code doesn’t work for any reason, the page will still go to the targeted location.

标准的锚链接用作该技术的基础:这样,如果新的平滑滚动代码由于任何原因无法使用,则页面仍将转到目标位置。

Click me: I’m smoooooth.

This is the target, further down the page.

Obviously, the page needs to extend past the bottom of the viewport window for this technique to work: if the browser already displays all the page content, no scroll will take place. For that reason, you must ensure that sure that the page has plenty of content (or filler text).

显然,页面需要扩展到视口窗口的底部才能使该技术起作用:如果浏览器已经显示了所有页面内容,则不会发生滚动。 因此,您必须确保页面上有足够的内容(或填充文本 )。

滚动的两面 (Two Sides of Scrolling)

Somewhat confusingly, the Smooth Scrolling API is implemented in two ways: once as a CSS property, and again in JavaScript. Adding to this confusion is the fact that some browsers support the API, while others do not.

令人困惑的是,平滑滚动API的实现方式有两种:一种是CSS属性,另一种是JavaScript。 有些浏览器支持该API,而另一些浏览器不支持,这一事实加剧了这种混乱。

For the CSS method, the element that will be smooth-scrolled (frequently, but not exclusively, the body) needs to have a scroll-behavior of smooth applied in CSS:

对于CSS方法,要平滑滚动的元素(通常(但非排他性地,是body ))需要在CSS中应用smoothscroll-behavior

body {
	scroll-behavior: smooth;
}

UK English coders, note the spelling of scroll-behavior: no “u"!

英国英语编码人员,请注意scroll-behavior的拼写:否“ u”!

This is enough to make the effect work in the current version of Firefox, but browsers like Chrome need more work, as of this writing.

这足以使效果在当前版本的Firefox中起作用,但是在撰写本文时,像Chrome这样的浏览器需要更多的工作。

JavaScript方面 (The JavaScript Side)

Browsers that do not support the scroll-behavior CSS property will need to use the JavaScript API, and most of those will need a polyfill: I would recommend Dustan Kasten’s smoothscroll, although there are many other possibilities.

不支持scroll-behavior CSS属性的浏览器将需要使用JavaScript API,并且大多数浏览器将需要polyfill :我建议Dustan Kasten的smoothscroll ,尽管还有很多其他可能性。

Let’s imagine that we have a

你可能感兴趣的:(css,javascript,js,html,java,ViewUI)