简体   繁体   中英

How to move HTML elements when a page is scrolled?

How to make an HTML element that is initially 'fixed' then when we scroll the web page down or more specifically through the element, the element will move to the side or wherever we specify. And of course when we scroll the web page back up and pass the element, it will return to normal.

Please help if there is, I ask for an article or explanation of what to use and an example of the source code.

检查此图像以获取更多详细信息。

You can use sticky for that: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_sticky_element

div.sticky {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 0;
}

I'm using jQuery for something similar on my app. The following code will add the class of 'scroll-active' to the 'nav' when scrolled 10px, and removes it when there is nothing scrolled.

$(function () {
    $(window).on('scroll', function () {
        if ( $(window).scrollTop() > 10 ) {
            $('nav').addClass('scroll-active');
        } else {
            $('nav').removeClass('scroll-active',);
        }
    });
});

I think you can use this and add the necessary css to it on your added class to have it on the right side.

You'll probably need javascript for that, this might work for you if you don't want to use jQuery.

<div id="container">
  some content
</div>

and some javascript to define add a class:

window.addEventListener('scroll', function(e) {
  container = document.getElementById('container');
  // The 0 could be a larger threshold if you want to move it after scrolling a bit
  container.classList.toggle('scrolling', window.scrollY > 0); 
});

and then define your CSS:

#container {
  /* style when not scrolling */
}

#container.scrolling {
  /* style when scrolling */
  position: fixed;
}

here is a working jsfiddle: https://jsfiddle.net/96xvotpc/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM