使用jQuery检查div的百分比宽度并执行条件样式
我有十个进步的例子。所有这些都具有基于百分比的宽度 如果.progress的任何给定实例的宽度超过100%,我希望将其设置为红色背景,然后强制设置为100%宽度 有什么帮助吗 这是我无力的尝试使用jQuery检查div的百分比宽度并执行条件样式,jquery,html,css,Jquery,Html,Css,我有十个进步的例子。所有这些都具有基于百分比的宽度 如果.progress的任何给定实例的宽度超过100%,我希望将其设置为红色背景,然后强制设置为100%宽度 有什么帮助吗 这是我无力的尝试 if ($( '.progress' ).css("width") > '100%') { $(this).css('background-color', 'red'); // or $(this).addClass('red'); } 或 我认为%中的宽度在js中不可用,因
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;
});
+我刚才输入的是,
'100%'
没有任何意义,但是您忘记了有10个.progress
@adeneo的实例。是的,我正在用.each()
方法更新这个实例。
$('.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;
});