• Author: Chen Da Yu Tou
  • Making: KRISACHAN

preface

In daily development, we are certainly familiar with the word scroll.

For example, a custom scrollbar with JS works like a tiger because you don’t like the browser’s default style.

Or whoosh back to the top.

Or a title navigation to where you want to go.

But in the past, implementing these features was not so easy.

For example, if we want to implement a scroll back to the top feature, we might need to write down this code.

let timer = null;
let backTop = document.querySelector("#backTop");
backTop.addEventListener("click".() = > {
  cancelAnimationFrame(timer);
  let startTime = +new Date(a);let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  let totalTime = 300;
  timer = requestAnimationFrame(() = > {
    let lastTime = totalTime - Math.max(0, startTime - +new Date() + totalTime);
    document.documentElement.scrollTop = document.body.scrollTop =
      (lastTime * -scrollTop) / totalTime + scrollTop;
    timer = requestAnimationFrame(func);
    if(lastTime === totalTime) { cancelAnimationFrame(timer); }}); });Copy the code

(Disclaimer: pseudo code is not tested, if there are bugs, please forgive me.)

So, that means to write an animation that keeps changing the vertical scrolling distance of the current page until it reaches zero.

(Melon eater: “Is it difficult? You are too clumsy, uncle!” )

But over time, as Web apis and CSS specifications improve, features that we once thought would be a hassle to implement become easier. Let’s take a look at these improvements.

Scroll family in Web API

Let’s go to the interesting API in the KangkangScroll family.

Scroll and scrollTo

The Scroll () and scrollTo methods are Element interfaces for scrolling to a particular coordinate in a given Element.

The syntax is as follows:

  1. scroll/scrollTo(x, y)

    • x: Horizontal coordinate of the position to move the element.
    • y: The ordinate of the position the element is to move.
  2. scroll/scrollTo(options)

    Options supports left, top, and Behavior

    • top: Horizontal coordinate of the position to move the element.
    • left: The ordinate of the position the element is to move.
    • behavior: Motion mode of the element, if yesauto, there is no animation effect if it issmooth, is smooth scrolling.

Let’s have kangkang chestnuts:

The above example comes from THE GitHub repository dom-examples for MDN

The core JS code is as follows:

let scrollOptions;

const form = document.querySelector("form");
const leftInput = document.getElementById("left");
const topInput = document.getElementById("top");
const scrollInput = document.getElementById("scroll");

form.addEventListener("submit".e= > {
  e.preventDefault();
  scrollOptions = {
    left: leftInput.value,
    top: topInput.value,
    behavior: scrollInput.checked ? "smooth" : "auto"
  };

  window.scrollTo(scrollOptions);
});
Copy the code

scrollBy

The scrollBy() method is the Element interface that causes the Element to scroll a specific distance.

The syntax is as follows:

  1. scrollBy(x, y)

    • x: Horizontal coordinate of the position to move the element.
    • y: The ordinate of the position the element is to move.
  2. scrollBy(options)

    Options supports left, top, and Behavior

    • top: Horizontal coordinate of the position to move the element.
    • Lef:: The ordinate of the position the element is to move.
    • behavior: Motion mode of the element, if yesauto, there is no animation effect if it issmooth, is smooth scrolling.

Here’s another chestnut:

The core code is as follows:

let scrollOptions;

const form = document.querySelector("form");
const leftInput = document.getElementById("left");
const topInput = document.getElementById("top");
const scrollInput = document.getElementById("scroll");

form.addEventListener("submit".e= > {
  e.preventDefault();
  scrollOptions = {
    left: leftInput.value,
    top: topInput.value,
    behavior: scrollInput.checked ? "smooth" : "auto"
  };

  window.scrollBy(scrollOptions);
});
Copy the code

Mmmmm, yeah, just changing scrollTo to scrollBy in the DEMO above. Very clever

Let’s look at the compatibility of the three apis:

Mmmm, compatibility is very good.

(Eat melon masses: IE has no human rights ?????????)

Element.scrollIntoView

The element.scrollintoView () method scrolls the current Element into the viewable area of the browser window.

The syntax is as follows:

  1. scrollIntoView(alignToTop)

    AlignToTop is a Boolean value that defaults to true if left blank. Equivalent to {block: ‘start’, inline: ‘nearest’}.

    If true, the top of the element is aligned with the top of the visible area of the scroll area in which it is located. If false, bottom-aligned. Equivalent to {block: ‘end’, inline: ‘nearest’}

  2. scrollIntoView(scrollIntoViewOptions)

    ScrollIntoViewOptions an object containing the following properties:

    • behavior: Motion mode of the element, if yesauto, there is no animation effect if it issmooth, is smooth scrolling.
    • block: defines the vertical alignment. The value can bestart.center.endornearestOne of the. The default isnearest.
    • inline: defines the horizontal alignment. The value can bestart.center.endornearestOne of the. The default isnearest.

Let me explain to you what happens with block and inline options:

  • startAlign with the current element’s parent’s hair (top).
  • centerAligns with the stomach (middle) of the current element’s father.
  • endAlign with the current element’s parent jio (bottom).
  • nearestThe nearest rule: Go where the nearest is. If it’s in the middle, don’t move.

The element is considered standing (top down) if it is a block, or lying (left to right) if it is inline. Of course, this assumes the default writing-mode: Horizontal-tb.

A bit around? Come kangkang chestnuts: codepen. IO /krischan77/…

Ok, so that’s killing Matt, oh no, scroll family characteristics. (Discarded or ready to be discarded is not included.)

Finally, let’s also look at compatibility:

Well, it’s ok, IE is working…

At this point, we in the Web AP killed matt family, oh no, scroll family has introduced, like Element. ScrollIntoViewIfNeed apis that don’t dye hair (not standard), is introduced, interested can go to see what it can do.

CSS scroll

After sharing the scroll in JS, let’s look at the scroll in CSS.

scroll-behavior

When we talked about scroll in this JS, we mentioned a word called “behavior” several times.

Mmmm, so can you guess if this scroll behavior has anything to do with the behavior in JS?

Well, yes, you guessed it, it does.

(Melon eaters: “No one cares about you!”)

Scroll behavior, like the behavior in the scrollAPI above, is used to define the animation effect when a page is scrolling.

If it is defined as smooth, the page will scroll when it is triggered, and if it is defined as auto, it will teleport to the specified position as before. This refers to a trigger like clicking # Hash to jump to, rather than sliding the scrollbar.

See the DEMO in the first section of this article.

Compatibility is shown here:

Scroll Snap

CSS Scroll Snap is a relatively new independent CSS module. Its first official version CSS Scroll Snap module Level 1 was released on March 19, 2019.

The CSS Scroll Snap module captures and automatically slides a page container to the specified position of a specified element when it stops scrolling.

Give it to me giaogiao! This is a remarkable feature

It is divided into two parts, one acting on the scroll container, the other acting on the relative scroll child elements, the specific relationship is shown in the following table:

On the rolling container Applied to the scroll child
scroll-snap-type scroll-snap-align
scroll-padding scroll-snap-stop
scroll-margin

scroll-snap-type

The scroll-snap-type property specifies whether the current scrolling container can be captured and aligned, as well as the direction and severity of the execution.

Its optional direction values are:

  • x: Captures the position on the X-axis
  • y: Captures the position on the Y-axis
  • block: Captures the position on the block axis (logically the same as y)
  • inline: Captures the position on the inline axis (logically the same as x)
  • both: Captures the position in both directions

Its optional strict values are:

  • none: Default value, Mmmm, do nothing
  • proximity: a sensible value. If the element is in the container’s capture range, capture and scroll, otherwise leave it alone. The range is around 45%.
  • mandatory: a reliable point value, as long as there are parameters, stop scrolling will be sure to align.

Here’s what kangkang looks like:

The preceding DEMO is from the scrollsnap-type of MDN

scroll-snap-align

The scroll-snap-align property specifies the location of the capture child to be captured by the capture container. The possible values are as follows:

  • none: Default value, do nothing 0.0.
  • start: Align with the starting position.
  • end: Align with the end position.
  • center: Center and align.

The effect is as follows:

The above DEMO comes from Andy Adams’ Scrollsnap-align

scroll-snap-stop

Because the Scroll Snap element will have several capture positions, and the Scroll snap-stop element can control whether it will be captured after reaching these positions or not until it reaches the specified position. The optional attributes are as follows:

  • normal: Default value. The capture position can be ignored while scrolling.
  • alwaysWhen scrolling, you must not ignore the capture position, but also locate the position of the first capture element.

Chestnuts are as follows:

The above DEMO is from MDN’s scroll snap-stop

scroll-margin

Scroll margin is a shorthand property, and like margin, there are different logical properties to choose from. It sets the size of the outer border between the element and the scroll bar. Let’s look at two giFs to see the difference.

When we click # Hash to jump.

Common operation:

h3{}Copy the code

Added scrolltop:

h3 {
  scroll-margin-top: 5rem;
}
Copy the code

The DEMO above is from Chris Coyier’s Fixed Headers and Jump Links? The Solution is scroll-margin-top

From the above two demos, we can see a clear comparison. Assuming that the #hash navigation element changes the scroll margin, the final jump position will be bounded by the scroll margin value.

Not only that, let’s look at the following DEMO:

The above DEMO comes from Andy Adams’ scroll margin

When we set the scrollmargin of an element to the visible area of the Scroll, the browser will move it to the nearest scrollmargin of the current element.

The scroll margin copy properties are as follows:

  • scroll-margin-top
  • scroll-margin-right
  • scroll-margin-bottom
  • scroll-margin-left
  • scroll-margin-block
  • scroll-margin-inline
  • scroll-margin-block-start
  • scroll-margin-inline-start
  • scroll-margin-block-end
  • scroll-margin-inline-end

scroll-padding

The scroll-padding type is the same as the padding-margin type.

For a DEMO:

The above DEMO comes from Andy Adams’ scroll-padding

The scroll-padding property also has the following properties:

  • scroll-padding-top
  • scroll-padding-right
  • scroll-padding-bottom
  • scroll-padding-left
  • scroll-padding-block
  • scroll-padding-inline
  • scroll-padding-block-start
  • scroll-padding-inline-start
  • scroll-padding-block-end
  • scroll-padding-inline-end

The compatibility of the above apis is as follows:

CSS overscroll

overscroll-behavior

Overscroll behavior is the only property in Level 1, the CSS transition scroll behavior module, which was first released by W3C in June 2019.

Overscroll behavior allows you to control how your browser scrolls to boundaries.

It is also a shorthand attribute. The specific attributes are:

  • overscroll-behavior-x: Handles the behavior of the horizontal scroll bar when it scrolls to a boundary under normal conditions.
  • overscroll-behavior-y: Handles the behavior of the vertical scroll bar when it scrolls to a boundary under normal conditions.
  • overscroll-behavior-inline: withoverscroll-behavior-xThe same.
  • overscroll-behavior-block: withoverscroll-behavior-yThe same

The alternative values are:

  • auto: Default value.
  • contain: When an element is scrolled to the edge, it does not affect nearby scrolled elements.
  • none: When an element is scrolled to the edge, not only does it no longer affect neighboring scroll elements, but the default scrolling to the edge is blocked.

Chestnuts are as follows:

Use overscroll behavior: contain;

The default

The compatibility is as follows:

Extracurricular posture

Old and new logical attributes

In addition to the usual x, y, top, right, bottom, and left values, there are four less common values block, inline, start, and end.

So what is it?

In fact, the W3C has deliberately modified the logical properties of CSS to take into account the writing habits of non-Spanish ranking countries.

In a country like ours or the United States, documents are arranged from top to bottom, left to right, top, right, bottom and left are easy to understand.

But countries like Japan or Arabia, where the writing arrangement is not the same as ours, have some logical incongruity, such as:

  • In Arabia, theirpadding-leftThe direction is actually ourspadding-right
  • In Japan, theirpadding-leftThe direction is actually ourspadding-top

In this case, it’s a little weird. So the W3C has come up with a new logical attribute, which looks like this:

Old logical properties New logical properties
top inset-block-start
bottom inset-block-end
left inset-inline-start
right inset-inline-end
margin-top margin-block-start
margin-right margin-inline-end
margin-bottom margin-block-end
margin-left margin-inline-start
border-top border-block-start
border-right border-inline-end
border-bottom border-block-end
border-left border-inline-start
padding-top padding-block-start
padding-right padding-inline-end
padding-bottom padding-block-end
padding-left padding-inline-start
width inline-size
height block-size

To summarize, the horizontal coordinate is inline, the vertical coordinate is block, the start position is start, and the end position is end.

One last special effect

This is a effect written using the scroll behavior: smooth, we were hanging out with friends, we were doing a lot of activities. There is a game is “you draw I guess”, as the head of the planner, nature can not let go of this opportunity, then with the technology of a small show.

Let’s look at the effect first.

The source address is here:

Codepen. IO/krischan77 /…

Because the code is too long, I won’t post it completely, but the core logic is to use scroll behavior: smooth; To control the effect of #hash jumps, we use the History API to maintain normal urls in order not to pollute urls. That’s what it looks like:

let pageIndex = 1;
const urlChangeHandler = event= > {
  const { newURL } = event;
  const current = newURL.replace(/.+\#page\-(\d)/."$1");
  pageIndex = +current;
  console.log(pageIndex);
  history.pushState(
    {},
    window.location.href,
    window.location.origin + window.location.pathname
  );
};
window.onhashchange = urlChangeHandler;
Copy the code

You might as well try to use the mastered posture to add a little spice to life

Afterword.

Melon eating crowd: I read the whole article, did not see where there is with ninjutsu related content ah? Cheat me traffic, lose money.

Fish head: What if I didn’t? You promised to spoil me. What do you mean now?

The resources

  1. scrollIntoView block vs inline
  2. CSSOM View Module
  3. Element.scrollIntoView()
  4. CSS Scroll Snap Module Level 1
  5. CSS TRICK scroll-snap-type
  6. MDN scroll-snap-type
  7. CSS TRICK scroll-snap-align
  8. scroll-snap-stop
  9. scroll-margin
  10. scroll-padding
  11. Fixed Headers and Jump Links? The Solution is scroll-margin-top
  12. caniuse

Afterword.

If you like to discuss technology, or have any comments or suggestions on this article, you are welcome to add yu Tou wechat friends to discuss. Of course, Yu Tou also hopes to talk about life, hobbies and things with you. His wechat id is krisChans95