jquery - 使用 jQuery 检查 div 的百分比宽度并执行条件样式

标签 jquery html css

我有 10 个 .progress 实例。所有这些都有基于百分比的宽度。

如果 .progress 的任何给定实例的宽度超过 100%,我想将其设置为红色背景,然后强制为 100% 宽度。

有什么帮助吗?

这是我微弱的尝试。

if ($( '.progress' ).css("width") > '100%') {
     $(this).css('background-color', 'red');
     // or $(this).addClass('red');

}

最佳答案

我认为 % 中的宽度在 js 中不可用,所以我认为您应该尝试检查目标的宽度与其父级的宽度:

if ($('.progress').css("width") >== $('.progress').parent().css("width")) {
   $(this).css('background-color', 'red');
   // or $(this).addClass('red');
}

或者这样:

$('.progress').each(function(){
   var $target = $(this);
   if ($target.css("width") >== $target.parent().css("width")) {
      $target.css('background-color', 'red');
      // or $target.addClass('red');
   }
});

或者这样

$('.progress').css('background-color', function(_, color) {
    return $(this).width() > $(this).parent().width() ? 'red' : color;
});

关于jquery - 使用 jQuery 检查 div 的百分比宽度并执行条件样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22893316/

相关文章:

javascript - 使用来自 ajax 或 jquery.get() 的数据打印 div

css - 如何减少虚线下划线链接的差距?

javascript - 高度固定为 100% 的水平滚动

javascript - 单击表格中的 tr 时使用 JQuery 创建弹出窗口

javascript - 您是否忘记在 django 中注册或加载此标签

javascript - 带有选项和可访问方法的 jQuery 插件模板?

java - java中字符串和日期时间的转换方法

javascript - ul float 左列表上的边框底部问题,​​具有打开框功能

jquery - 如何在 HTML 和 CSS 中使背景静态化?

jquery - 为什么我的 PostBack 发生在 jQuery 单击事件之前?