繁体   English   中英

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

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

我正在一个页面上,其中有大约6个div具有相同类别的“bar”,但每个div的宽度根据用户的输入动态变化。 我现在需要做的是改变任何宽度为250px且类别为“bar”的div的颜色。 我的概念如下:

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

这基本上是我的概念,但我不知道如何实现这个效果。 如果有人能提供帮助,我们将不胜感激

谢谢。

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

如果你只有一个.bar元素,你提出的解决方案听起来应该有效,但你有多个。 如果你想在给定的时间间隔内继续运行它,我看到的另一件事是潜在的,所以无论何时动态改变这些框,你都会应用效果。

$(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');
    }
  });
}

编辑:每次调整窗口大小时,将在每个500毫秒调用效果,同时用户调整大小以避免资源占用每个窗口调整大小差异的函数调用。

暂无
暂无

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

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