Different from Jquery, Remove class when width screen is 1050px

强颜欢笑 提交于 2019-12-11 14:44:59

问题


OK i know now how to remove abd add class with the width of the window.

But now i'm struggling with this issue:

I want this:

 var num = 90; //number of pixels before modifying styles

$(window).bind('scroll', function () {
    if ($(window).scrollTop() > num) {
        $('#menu2').addClass('f-nav');
    } else {
        $('#menu2').removeClass('f-nav');
    }
});

to work with this:

function checkWidth() {
    if ($(window).width() > 1049) {
        $('#menu2').addClass('f-nav');
    } else {
        $('#menu2').removeClass('f-nav');
    }
}

$(window).resize(checkWidth);

So in other words,

When i scrolldown it must add a class, but when it resizes it must remove the class + it also has to be removed when i scroll up.


回答1:


According to your comment @Lashus's answer

|      | > 1050px | < 1050px |
+----------------------------+
| top  | -        | -        |
| down | + f-nav  | - f-nav  |

This means, do nothing at the top, but add or remove f-nav, when scrolled down

$(window).bind('scroll', function () {
    if ($(window).scrollTop() > num)
        checkWidth();
});

JSFiddle

Also note the comment for .bind() vs. .on()

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.




回答2:


You cannot change a class without using javascript in that case. However you can use CSS Media queries to change the behaviour of given class on different devices.

Example below:

(CSS)
.f-nav {
    color: #fff;
}

@media screen AND (max-width: 1050px) {
    .f-nav {
        color: #000;
    }
}


来源:https://stackoverflow.com/questions/20472801/different-from-jquery-remove-class-when-width-screen-is-1050px

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!