Implementation ideas
- Get the offsetTop of the current dom node relative to offsetParent, and save this offsetTop (prevent the offsetTop when the current dom position is fixed to reset to 0).
- Listen to the page sliding distance. When the sliding distance -offsetTop>0, the current dom node will cap, otherwise it will restore the previous state.
Implement code
Without further ado, the code is added:
export default { stick: { bind: (el, binding, vnode) => { let oldOffsetTop = null; // Save the offsetTop of the current element to prevent the offsetTop from resetting to 0 after ceiling addEventListener('scroll', e => { const scrollTop = || || // Rolling distance const { offsetTop } = el // The distance of the element from offsetParent if (!oldOffsetTop) oldOffsetTop = offsetTop if (scrollTop - oldOffsetTop > 0) { = 'fixed' if () { = + 'px' } else { = '0px' } } else { if ( === 'fixed') { = 'static' } } }) } } }
The above code implements a vue instruction with ceiling effect, and in the end, you only need to register this instruction in the file to use it.
Add to the file
import directive from './common/directive' for (const key in directive) { (key, directive[key]) }
How to use:
<li class="stick" v-stick>Ceiling effect command</li>
Or add an offset
<li class="stick" v-stick="100">Ceiling effect command</li>
<template> <div > <!-- <starrySky /> --> <div class="p"></div> <ul> <li>1</li> <li>1</li> <li>1</li> <li>1</li> <li>1</li> <li>1</li> <li>1</li> <li>1</li> <li>1</li> <li>1</li> <li>1222222</li> <li class="stick" v-stick>Ceiling effect command</li> <li>12222222</li> <li>1</li> <li>1</li> <li>1</li> <li>1</li> <li>1</li> <li>1</li> <li>1</li> </ul> </div> </template> <script> export default { components: { } } </script> <style> #app { } .p { height: 100vh; } ul { } li{ padding: 30px; } </style>
This is the end of this article about using vue instructions to achieve ceiling effects. For more related content on vue instructions to achieve ceiling effects, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!