Vue simple ceiling effect to achieve sticky in vue does not work alternatives

The ceiling effect needs to be realized in the vue project, but the sticky doesn't work, and the v-sticky plug-in doesn't work either.

After consulting the data, I found that the reasons why sticky does not work are:

1) The parent element has overflow:hidden or overflow:auto set

2) Any one of the 4 values ​​of top, right, bottom, and left is not specified

3) The height of the parent element is smaller than the height of the element positioned by sticky

The sticky property switches between position:relative and position:fixed positioning depending on the user's scrolling. Element positioning behaves as relative positioning until a certain threshold is crossed, and fixed positioning thereafter.

But my components are all satisfied, but I just can't achieve the ceiling effect, and there is no reaction at all. Forget it, I don't need components and sticky. I write an alternative method by myself, and it is convenient to modify it according to the needs later.

sticky alternative

1. Effect simulation:

2. Idea: When the nav slides normally, position: relative, detect the distance between the component and the top of the interface, and when it slides to the top, reset position: fixed, top: 0px; to achieve the ceiling.

3. Code:

<nav :style="stickyChange"></nav>
<script>
    export default {
        name: "MidNav",
        data(){
            return{
                stickyChange:"position:relative;z-index:0",
              }
        },
        methods:{
            getScroll(e){
                //手机端只能通过e.target.scrollTop获取组件的滑动距离
                let topDis = window.pageYOffset || document.documentElement.scrollTop || 
                             document.body.scrollTop||e.target.scrollTop;
                //此处660为测试组件滑动到顶部的距离;
                if (topDis>=660){
                    this.stickyChange="position:fixed;top:0px;opacity: 0.98;z-index:999";
                   
                }else{
                    this.stickyChange="position:relative;z-index:0";
  
                }
            },
        },
        mounted() {
            //添加动态监听
            window.addEventListener('scroll',this.getScroll,true);
        }
        
  }
</script>

 Steps: 1) Set the changed style attribute: :style="stickyChange"

2) Add changed data: data binding style attribute, change style by method, stickyChange: "position: relative; z-index: 0"

3) Add sliding monitoring in the mounted method:

window.addEventListener('scroll',this.getScroll,true);

4) Implement the monitoring method: getScroll(e)

Guess you like

Origin blog.csdn.net/qq_43780761/article/details/126132418