Getting to the actual front-end development: CSS smooth page scrolling

1. The slow pace of their own

Over the years he spent a great deal of study in the field of energy accessibility, SVG and Canvas these small congregation, so many front-end new features, new technology failed to timely attention and understand that there are new CSS3 properties of the field, there are areas JS the new API, including the new ES6 / ES7 grammar, etc., compared to the previous study, the pace is really slow. For example, this article will introduce smooth scrolling, either CSS or JS, modern browsers offer a property or method native, but has been almost a year, and I recently learned that several years ago, real-time attention to new technologies themselves form a clear contrast.

But with SVG and Canvas foundation more solid, more in-depth details, I have begun to learn the breadth direction of the center of gravity shift, and slowly pick up those ears of corn left behind.

2. from dry to wet and slippery

Assuming that there is a page following paragraph HTML:


<a href="#" rel="internal">返回顶部</a>

Help us click on the "Top" This text link when the page will be "shabu" to cry instantly locate to the top of the browser, fast speed, fierce rally that you do not have any reaction, just like a storm of love let you off guard, brain constantly recalled: "??? where am I who I am, what I just did."

All these reactions produce the final analysis that our rolling effect is too dry, and no mechanical blunt spirituality understand style.

People are emotional animals, since we do with the website is to give people, it is naturally full of emotion, not so dry, so wet and slippery rolling effect, the user experience will be good.

Snow smooth skin, full lips moist, is not always people s heart? If we interactivity could do so, it also allows users to heart.

The browser seems to have realized this, from the end of last year, has begun to support browser's native smooth scrolling positioning, CSS  scroll-behaviorproperties and JS  scrollIntoView()method can be.

scroll-behavior Browser Compatibility

Two, CSS scroll-behavior and smooth scrolling

scroll-behavior:smoothWritten on the scroll of the container element, you can let the container (non-mouse gesture triggers) become smooth scrolling.

The initial value is 'auto'.

Simpler and more practical uses

In fact, scroll-behaviorusing not so much flower head, you remember such a sentence -

Those who need to scroll the places plus a scroll-behavior: smooth enough!

Do not worry about him not get used, how they do not control the browser compatibility, you can add. It's like a free lottery money do not win, it does not matter, and nothing to lose, winning the good nature, icing on the cake! scrol-behavior:smoothThis is urinary.

For example, in the PC browser, the default Web page scrolling is &lt;html&gt;on the label, in most mobile end &lt;body&gt;on the label, so I add such a sentence:

html, body { scroll-behavior:smooth; }

In this case, click on the following "Top" link, you will smooth scroll to the top (True real-time results, you can click on the try).

HTML code is as follows:

<a href="#">返回顶部</a>

From this point of view, CSS reset the browser industry can add such a rule:

html, body { scroll-behavior:smooth; }

Three, JS scrollIntoView with smooth scrolling

DOM elements scrollIntoView()method is a IE6 browser also supports native JS API, allowing the elements to enter the viewing area, the positioning achieved by triggering the rolling container.

With Chrome and Firefox browsers began to support CSS  scroll-behaviorproperty, by the way right, scrollIntoView()the method has been upgraded to support the additional parameters, which can make an argument that is smooth scrolling.

The syntax is as follows:

target.scrollIntoView({
    behavior: "smooth"
});

We just have to open a linked page, the first link scroll off the screen, and then enter the console similar to the code below, we can see the positioning of the smooth scrolling page:

document.links[0].scrollIntoView({
    behavior: "smooth"
});

Video screenshot below:

other:

  • scrollIntoView()After the upgrade method, in addition to support 'behavior', as well as 'block'and 'inline'other parameters, we are interested can refer to the MDN documentation.
  • If our website has been set up by CSS scroll-behavior:smoothdeclaration, then we direct execution target.scrollIntoView()method will be smooth scrolling, no longer need to set additional behaviorparameters. For example, if you are browsing in the original Xin space station this article, open the console, execute the code below, you can see the effect of smooth scrolling:
document.forms[0].scrollIntoView();

Four, JS smooth scrolling backward compatible processing

JS is not difficult to achieve smooth scrolling, jQuery in the animate()method:

scrollContainer.animate({
    scrollTop: 0
});

Or use requestAnimationFrame API such native JS can be achieved. For example, the following sketch of my methods:


/**
 @description 页面垂直平滑滚动到指定滚动高度
 @author zhangxinxu(.com)
*/
var scrollSmoothTo = function (position) {
    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function(callback, element) {
            return setTimeout(callback, 17);
        };
    }
    // 当前滚动高度
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    // 滚动step方法
    var step = function () {
        // 距离目标滚动距离
        var distance = position - scrollTop;
        // 目标滚动位置
        scrollTop = scrollTop + distance / 5;
        if (Math.abs(distance) < 1) {
            window.scrollTo(0, position);
        } else {
            window.scrollTo(0, scrollTop);
            requestAnimationFrame(step);
        }
    };
    step();
};

Using your own possession easing animation JS small algorithm, rolling slow down after.

Use the following example, we want to smooth scrolling to the top of the page directly:

scrollSmoothTo(0);

On it.


How difficult is it to support smooth scrolling of the browser native processing, does not support the browser or use the old method of JS processing.

JS I was such a deal the following judgment:

if (typeof window.getComputedStyle(document.body).scrollBehavior == 'undefined') {
   // 传统的JS平滑滚动处理代码...
}

This allows seamless docking.

V. Conclusion Conclusion ending language

No personal qualities articles like machines without a soul is. Miss Zhang Yun photos, do not trust the leadership of the house, for fear of copyright infringement came to the door, gave out the next, and now those photos of beautiful women, just like drinking water, as uninteresting ......

I'm wondering to change roles or labels, such as ...... a horse!

Here's the tip I recommend learning exchange circle: 767 273 102, which is learning from the most basic HTML + CSS + JS [cool special effects, games, plug-in package design patterns] to move the front end of HTML5 project real learning materials We are finishing, given to every small front-end partner. 2019 the latest technology, synchronization and business needs. Friends are inside learning exchanges, there will be a big cow every day to explain the timing of front-end technology!

Learning the front, we are serious

Guess you like

Origin blog.51cto.com/14284898/2404478