jquery if width is less than, change this attr

二次信任 提交于 2019-12-08 07:31:12

问题


    $(".section").each(function(i, el){
    var section = $('.section');
    var width = section.width();
    if (width < 960)
        section.attr('class', 'section-slim');
});

This seems to work fine, on browser refresh, how do I make it act when resized? Ex: if someone makes their browser window smaller, it will add this class?


回答1:


bind the event to jQuery's "resize" event

$(window).on("resize load", function () {
    $(".section").each(function(i, el){
    var section = $('.section');
    var width = section.width();
    if (width <= 960) {
        section.attr('class', 'section-slim');
    }
})



回答2:


Put your code in one common function than call it from window.resize()

$(window).resize(function() { //you can call your function here
    // do something here
});


来源:https://stackoverflow.com/questions/11377831/jquery-if-width-is-less-than-change-this-attr

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