简体   繁体   English

固定 div 滚动

[英]Fixed div on scroll

I'm trying to create a div which will get a class only on scrolling and when the value of scroll is 210. I have next code :我正在尝试创建一个 div,它只会在滚动时获取一个类,并且当 scroll 的值为 210 时。我有下一个代码:

$(document).ready(function() {
    var pageWidth = $(window).width();

    if(pageWidth > 700){
        var contentLeft = $('#content-left');
        var height = 210;

        $(window).scroll(function () {
            if ($(window).scrollTop() < height) {
                contentLeft.attr('class', 'content-left');
            } else {
                contentLeft.attr('class', 'content-left leftContentFixed');
            }
        });
    }
});

I try to apply this only on desktops.我尝试仅在台式机上应用它。 Thus, I do not need the class leftContentFixed if it's on a smartphone or tablet.因此,如果它在智能手机或平板电脑上,我不需要 leftContentFixed 类。

If I try something like :如果我尝试类似的东西:

$(document).ready(function() {
    var pageWidth = $(window).width();

    if(pageWidth > 700){
        alert("Bigger than 700");
    }else{
        alert("Smaller than 700");
    }
});

Than it works perfect, but with my code it isn't working.比它完美,但用我的代码它不起作用。 The class leftContentFixed is added although the screen is smaller than 700.尽管屏幕小于 700,但添加了 leftContentFixed 类。

Any advice?有什么建议吗?

You need to check screen size on resize event and check for its value when user scrolls the page.您需要在resize事件时检查屏幕大小,并在用户滚动页面时检查其值。 You could create mobile variable and make it true/false depends on screen size, then in scroll callback check for its value and choose correct class.您可以创建mobile变量并使其true/false取决于屏幕大小,然后在scroll回调中检查其值并选择正确的类。

 $(document).ready(function() { var pageWidth = $(window).width(), height = 210, contentLeft = $('.content-left'), mobile = false; $(window).on('load resize', function() { pageWidth = $(this).width(); // Save mobile status if (pageWidth > 700) { mobile = false; } else { mobile = true } }) $(window).on('scroll', function() { if ($(window).scrollTop() > height) { // Set default class var _class = 'content-left leftContentFixed'; // If mobile then modify class if (mobile) { _class = 'content-left'; } contentLeft.attr('class', _class); } else { var _class = 'content-left'; contentLeft.attr('class', _class); } }); });
 html { height: 2000px } .content-left { background: gold; width: 50px; height: 100px; } .content-left.leftContentFixed { position: fixed; top: 0; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content-left"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM