Back to top

Time:2021-8-25

Anchors and smooth scrolling

stay<html>Provides an ID targeted link on the element

<div id="top"></div>
< a href = "#top" > jump to the top of the page</a>

We can use the latestscroll-behaviorProperty to achieve CSS smooth scrolling

html {
  scroll-behavior: smooth;
}

View effect

scrollTo、scrollBy、scrollIntoViwe

Add the root node firstscroll-behaviorProperty to achieve CSS smooth scrolling

html {
  scroll-behavior: smooth;
}

Next, add a click event to the button and use it at any timescrollToscrollByorscrollIntoViweMethod to scroll to the top.

Window.scrollTo()Scroll to a coordinate in the document.

Elem.scrollTo()Method to scroll the interface to the specified coordinate position of a given element.

window.scrollTo(0, 0)
document.documentElement.scrollTo(0, 0)

Window.scrollBy()Scroll the document in the window at the specified offset.

Elem.scrollBy()The method is to make the element scroll a specific distance.

window.scrollBy(0, -100000)
document.documentElement.scrollBy(0, -100000)

Window.scroll()Scroll the window to a specific location in the document.

Elem.scroll()Method is used to scroll to a specific coordinate in a given element.

window.scroll(0, 0)
document.documentElement.scroll(0, 0)

Elem.scrollIntoViwe(top)The page will be scrolled so thatElemso

  • top=true(default), scroll the page so thatElemAppears at the top of the window. The top edge of the element aligns with the top of the window.
  • top=false, scroll the pageElemAppears at the bottom of the window. The bottom edge of the element aligns with the bottom of the window.
document.documentElement.scrollIntoView()

View effect

Detect scroll position: scroll event

  • usedocument.documentElementReturns the root element of the document, which we need to get the offset value
  • Add on buttonclickEvent listener. stayscrollToTopFunction, usingscrollToMethod to scroll it to the top of the screen.
const scrollToTopBtn = document.querySelector('.scrollToTopBtn')
const rootElement = document.documentElement

const scrollToTop = () => {
  rootElement.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

scrollToTopBtn.addEventListener('click', scrollToTop)

Next is the display button, and we can use the scroll event listener to detect scrolling.

handleScrollThe function is called every time the user scrolls. Now we need the total number of pixels that can be scrolled.

  • Element.scrollHeightRead only property. Gives the content height of the element, including parts that are not visible due to overflow.
  • Element.clientHeightRead only property. Gives the internal height of the element (in pixels), that is, the height of the visible part, including the inner margin, but excluding the horizontal scroll bar, border and outer margin.
function handleScroll() {
  const scrollTotal = rootElement.scrollHeight - rootElement.clientHeight
  if ((rootElement.scrollTop / scrollTotal) > 0.80) {
    scrollToTopBtn.classList.add('showBtn')
  } else {
    scrollToTopBtn.classList.remove('showBtn')
  }
}

document.addEventListener('scroll', handleScroll)

View effect

Intersection Observer API

Intersection Observer APIProvides a way to asynchronously observe changes where the target element intersects the ancestor element or the viewport of the top-level document.

Compared with the previous scroll event listening scroll, the intersection observer API is an excellent solution to solve such problems. This is a fairly new browser API that allows developers to delegate most tasks to browsers in a more optimized way.

const target = document.querySelector('footer')
const scrollToTopBtn = document.querySelector('.scrollToTopBtn')
const rootElement = document.documentElement

//Once the footer enters or leaves the viewport, classes are added or removed. The callback receives the entries array as a parameter.
function callback(entries, observer) {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      scrollToTopBtn.classList.add('showBtn')
    } else {
      scrollToTopBtn.classList.remove('showBtn')
    }
  })
}

const observer = new IntersectionObserver(callback)
observer.observe(target)

function scrollToTop() {
  rootElement.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

scrollToTopBtn.addEventListener('click', scrollToTop)

View effect

Animate requestanimationframe

window.requestAnimationFrame()Tell the browser that you want to execute an animation and ask the browser to update the animation before calling the specified callback function before next redraw. This method needs to pass in a callback function as a parameter, which will be executed before the next redrawing of the browser

  • Element.scrollTopProperty to get or set the number of pixels in which the content of an element scrolls vertically.
  • usewindow.requestAnimationFrame()To animate scrolling.
const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop)
    window.scrollTo(0, c - c / 8)
  }
}

View effect

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]