问题
$(".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