简体   繁体   中英

How to use jQuery to get an element with a certain width?

I'm working on a page where there's about 6 divs with the same class of "bar", but the width of each div is dynamically changing based on user's input. What I need to do now is to change the color of any div that is 250px in width and with the class of "bar". My concept is as followed:

if($('.bar').width() == 250) {
    $(this).addClass('barColor');
}
else {
    $(this).removeClass('barColor');
}

That's basically my concept but I don't know how to achieve the effect. It will be greatly appreciated if anyone could help

Thank you.

$('.bar').each(function(){
    if($(this).width() == 250) 
        $(this).addClass('barColor');
    else
        $(this).removeClass('barColor');
}).

You proposed solution sounds like it should work if you only have one .bar element, but you have multiple. The other thing that I see is potentially if you want to keep running it at a given interval, so whenever these boxes are dynamically changed, you would have the effect applied.

$(window).resize(function() {
  clearTimeout(this.id);
  this.id = setTimeout(adjustClass, 500);
});

function adjustClass() {
  $('.bar').each(function() {
    if $(this).width() == 250) {
      $(this).addClass('barColor');
    }
    else {
      $(this).removeClass('barColor');
    }
  });
}

EDIT: Every time the window is resized, the effect will be called every 500 millisecond while the user is resizing to avoid resource hog for function call for every window resize difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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