我有 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/