滚动到元素时添加粘性类

时间:2019-03-07 16:36:55

标签: javascript vue.js

我的vue组件中有一个元素,我想在用户滚动通过它时应用一个固定的类,但是它没有生效,并且我可以看到粘性console.log触发了每个滚动,而不仅仅是在元素滚动时通过了。我也想在没有通过元素时删除该类。

这是我带有jquery代码的组件。

<template>
<div id="sticky" style="width:35%; height:85vh; padding:0px 0px; margin:0px 0px 0px auto; background-color:rgb(10,10,10); display:flex; flex-direction:column; position:relative; border:5px solid #9d0000; overflow:hidden; outline:2px solid red;">
        </div>
    </div>
</template>
<!--SCRIPTS-->
<script>
import $ from 'jquery';
export default {
name: 'CARTmodal2',


mounted() {
    console.log(this.$options.name+' component successfully mounted');

    let sticky = $('#sticky'),
    stickyTop = sticky.offset().top,
    scrolled = false,
    $window = $(window);

    /* Bind the scroll Event */
    $window.on('scroll', function(e) {
        scrolled = true;
    });

    let timeout = setInterval(function() {
        /* If the page was scrolled, handle the scroll */
        if (scrolled) {
            scrolled = false;
            if ($window.scrollTop() >= stickyTop) {
                sticky.addClass('fixed');
                console.log("sticky");
            }
            else {
            sticky.removeClass('fixed');
            }
        }
    }, 200);


},



};
</script>
<style scoped>
.fixed{position:fixed; top:0px; left:0px; border:1px slid black;}
</style>

知道我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

问题是您要在Vue生态系统的外部添加类,Vue会替换更新中包含的类,这会忽略您的外部更改,使用内部条件和:class="{'fixedClass':isScrolled}"参数来添加或删除它。 / p>

也许这个示例如何创建固定的标头可以帮助您处理滚动事件。

https://www.w3schools.com/howto/howto_js_sticky_header.asp

相关问题