Check scrolling with CSS

2019-01-18 10:46发布

问题:

I am trying to create a pure 100% CSS (no jQuery) "Back to Top" button but I would like the button to show only if the visitor scrolls down the page.

Is it possible to check that with CSS somehow? So if visitor scrolled down a bit show the "Back to Top" button.

Thanks!

回答1:

Determine by Cursor Location

One way you could do this would be to only show the .toTop element when the user is hovering over the content of the page itself, well below the header, and navigation links:

.toTop { opacity: 0; }
.toTop:hover, main:hover + .toTop { opacity: 1; }

You can see the effect here: http://jsfiddle.net/GFfbe/1/

Or, Slowly Uncover It

Alternatively, you could slowly uncover the .toTop link with another element. In the example below, I use the body's pseudo element ::before to cover up the .toTop element, and slowly reveal it as the user scrolls:

/* .toTop will appear in the left margin */
body {
    margin: 0 10em;
}

/* Positioned and sized to overlap .toTop */
body::before {
    content: "";
    background: white;
    position: absolute;
    bottom: 0; left: 0;
    width: 100%; height: 5em;
}

/* Positioned, so body::before goes behind it */
main {
    position: relative;
}

/* Attached to viewport at bottom left */
.toTop {
    z-index: -1;
    position: fixed;
    bottom: 1em; left: 1em;
}

You can see this effect here: http://jsfiddle.net/GFfbe/2/



标签: css scroll