简体   繁体   English

如何使用jQuery获取具有一定宽度的元素?

[英]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. 我正在一个页面上,其中有大约6个div具有相同类别的“bar”,但每个div的宽度根据用户的输入动态变化。 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". 我现在需要做的是改变任何宽度为250px且类别为“bar”的div的颜色。 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. 如果你只有一个.bar元素,你提出的解决方案听起来应该有效,但你有多个。 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. 编辑:每次调整窗口大小时,将在每个500毫秒调用效果,同时用户调整大小以避免资源占用每个窗口调整大小差异的函数调用。

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

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