SoFunction
Updated on 2025-04-11

Use vue command to achieve ceiling effect

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>

&lt;template&gt;
&lt;div &gt;
  &lt;!-- &lt;starrySky /&gt; --&gt;
  &lt;div class="p"&gt;&lt;/div&gt;
  &lt;ul&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1222222&lt;/li&gt;
   &lt;li class="stick" v-stick&gt;Ceiling effect command&lt;/li&gt;
   &lt;li&gt;12222222&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
   &lt;li&gt;1&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;

export default {
  components: {
  }
}
&lt;/script&gt;

&lt;style&gt;

#app {
}
.p {
  height: 100vh;
}
ul {
}
li{
  padding: 30px;
}
&lt;/style&gt;

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!