I’ve spent most of my time working on b-side projects, and when I do that, I usually do it directlyaTag done, now that we’re on the C side, the requirements for interactivity are going up, at this pointaLabels are far from meeting the requirements, and need to use JS to achieve such requirements, which is hereby recorded.

A label

So let’s put out the HTML

<body>
    <contain class="test1">
        <a name="topAnchor"></a>
        <div id="top">I was at the top of the</div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </contain>
    <footer>
        <button id="backTop1">The first way is back to the top</button>
        <button id="backTop2">The second way is back to the top</button>
        <button id="backTop3">The third way is back to the top</button>
    </footer>
</body>
Copy the code

Then the specific operation steps are as follows

  1. Places the A tag near the specified element
  2. It is then generated by clicking the eventaThe label
  3. The triggeraTag event
  4. deleteaThe label

The following code

    const backTop1 = document.getElementById("backTop1")

    backTop1.addEventListener("click".function (e) {
        let a = document.createElement("a")
        a.href = "#topAnchor"
        e.target.appendChild(a)
        a.onclick = function (e) {
            e.stopPropagation()
        }
        a.click()
        e.target.removeChild(a)
    })
Copy the code

The effect is shown below

The effect is obvious, as soon as the event is triggered, the page goes to the top of the page. This is fine when the interactivity is not very demanding, but when it is too demanding, it becomes a bit obtrusive. You can set HTML in style, body {scroll-behavior:smooth; }, can achieve the same effect as the following two apis whose behavior parameter is smooth

scrollTo()

This API needs to pass the distance between the LEFT and top of the DOM element relative to the window. This example is just a simple demo, only considering the top coordinate. Of course, it also has a behavior parameter, which is set to smooth, and the sliding effect will appear as follows:

  1. Calculates the distance of the target element from the top
  2. Triggered by an event

The code is as follows:

    const backTop2 = document.getElementById("backTop2")
    const TOP = document.getElementById("top")
    const y = TOP.offsetTop
    const backTop3 = document.getElementById("backTop3")
    backTop3.addEventListener("click".function (e) {
        window.scrollTo({ top: y, left: 0.behavior: 'smooth'})})Copy the code

The effect is shown below

In effect, this API supports animation compared to the A tag, making the page smoother. However, it does not support iframes enough. In the projects I have encountered, iframes account for a large proportion, so please use them with caution

Element.scrollIntoView()

Compared with the previous API, the node information is more clear and the operation method is more concise, which is more conducive to the subsequent maintenance code as follows

    const backTop2 = document.getElementById("backTop2")
    const TOP = document.getElementById("top")
    backTop2.addEventListener("click".function (e) {
        TOP.scrollIntoView({ behavior: "smooth"})})Copy the code

The effect is shown below

In effect, the API and scrollTo work the same way, but in terms of code structure, scrollIntoView is much cleaner and performs better in iframes, and is generally used more often

After digg friend tip, the above three animation effects have some compatibility problems, originally said yesterday to deal with, the result yesterday overtime too late, to pigeon talk no more, start to the topic:

The generic version of JS controls back to the top of the page

	const distance=70;// The distance of each scroll bar
    function up(){
        let  start = document.documentElement.scrollTop;
        function gotop() {
            scrollTo(0, start - distance)
            start = start - distance
            if (start >0) {window.requestAnimationFrame(gotop)
            }
        }
        window.requestAnimationFrame(gotop)
    }
Copy the code

RequestAnimationFrame (backTop, elementUi, requestAnimationFrame) The source code is as follows:

const cubic = value= > Math.pow(value, 3);
const easeInOutCubic = value= > value < 0.5
  ? cubic(value * 2) / 2
  : 1 - cubic((1 - value) * 2) / 2;
  
    scrollToTop() {
      const el = this.el;// el If it is a box, the scroll bar will scroll in the box, if not passed, the entire page
      const beginTime = Date.now();
      const beginValue = el.scrollTop;
      const rAF = window.requestAnimationFrame || (func= > setTimeout(func, 16));
      const frameFunc = () = > {
        const progress = (Date.now() - beginTime) / 500;
        if (progress < 1) {
          el.scrollTop = beginValue * (1 - easeInOutCubic(progress));
          rAF(frameFunc);
        } else {
          el.scrollTop = 0; }}; rAF(frameFunc); }Copy the code

It uses a mathematical curve to scroll, no matter how high the page content, back to the top is the same time, I write more rigid, directly write dead 70, 囧. If you are interested, you can go to the source of Element UI portal