[英]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.如何制作最初“固定”的 HTML 元素,然后当我们向下滚动 web 页面或更具体地通过元素时,该元素将移动到侧面或我们指定的任何位置。 And of course when we scroll the web page back up and pass the element, it will return to normal.
当然,当我们向后滚动 web 页面并传递元素时,它会恢复正常。
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您可以为此使用粘性: 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.我在我的应用程序上使用 jQuery 进行类似的操作。 The following code will add the class of 'scroll-active' to the 'nav' when scrolled 10px, and removes it when there is nothing scrolled.
以下代码将在滚动 10px 时将 'scroll-active' 的 class 添加到 'nav' 中,并在没有滚动时将其删除。
$(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.我认为您可以使用它并在添加的 class 上添加必要的 css 以使其位于右侧。
You'll probably need javascript for that, this might work for you if you don't want to use jQuery.为此,您可能需要 javascript,如果您不想使用 jQuery,这可能对您有用。
<div id="container">
some content
</div>
and some javascript to define add a class:和一些 javascript 来定义添加一个 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:然后定义你的 CSS:
#container {
/* style when not scrolling */
}
#container.scrolling {
/* style when scrolling */
position: fixed;
}
here is a working jsfiddle: https://jsfiddle.net/96xvotpc/2/这是一个有效的jsfiddle: https://jsfiddle.net/96xvotpc/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.