with locomotivescroll i want Fixed elements on scrolling a div
To fix elements on scrolling a div using LocomotiveScroll, you can use the following steps:
- Add the LocomotiveScroll library to your project.
- Create a container div with a fixed height and set its position to relative.
- Add the content you want to scroll inside the container div.
- Create a fixed div outside the container div and add the content you want to fix inside it.
- Use the LocomotiveScroll event listener to detect the scroll position of the container div.
- When the scroll position reaches a certain point, add a class to the fixed div to fix it in place.
- When the scroll position goes back to the top, remove the class to allow the fixed div to scroll again.
Here's an example code snippet:
HTML:
<div id="container">
<!-- content to scroll -->
</div>
<div id="fixed">
<!-- content to fix -->
</div>
CSS:
#container {
position: relative;
height: 500px; /* set a fixed height */
overflow-y: scroll; /* enable vertical scrolling */
}
#fixed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100px; /* set a fixed height */
background-color: #fff; /* add some styling */
}
.fixed {
position: fixed;
top: 0;
left: 0;
z-index: 1; /* make sure the fixed element is on top */
}
JavaScript:
const scroll = new LocomotiveScroll({
el: document.querySelector('#container'),
smooth: true
});
scroll.on('scroll', () => {
const container = document.querySelector('#container');
const fixed = document.querySelector('#fixed');
if (container.scrollTop > 100) {
fixed.classList.add('fixed'); /* add the fixed class */
} else {
fixed.classList.remove('fixed'); /* remove the fixed class */
}
});
This code will fix the #fixed element on scrolling the #container element once the scroll position goes beyond 100 pixels from the top. You can adjust the scroll position and styling to fit your needs
原文地址: https://www.cveoy.top/t/topic/ccNf 著作权归作者所有。请勿转载和采集!