gpt4 book ai didi

javascript - 如何根据元素的宽度改变背景颜色?

转载 作者:行者123 更新时间:2023-11-28 13:14:49 24 4
gpt4 key购买 nike

我正在尝试制作一个进度条。 HTML 如下:

<div class="progress-bar" style="width:5%"></div>

我想根据它的宽度绘制 DIV 的背景。比如小于100(返回值以px为单位),我要给它涂上红色。

我尝试了以下方法:

var currentWidth = $('.progress-bar').width();
if (currentWidth < 100) {
$('.progress-bar').css('background-color','red');
}

Here is the demo on JSFiddle.

但它不是画它。

我不习惯使用 javascript 和 jquery,所以我认为这可能是语法错误或我看不到的东西。任何人都可以帮助我如何让它工作吗?

提前致谢。

最佳答案

您的代码没问题。唯一的事情是指定 height

<div class="progress-bar" style="width:5%;height:5px"></div>

你应该看起来很像

$(function () {
var currentWidth = $('.progress-bar').width();
console.log(currentWidth);
if (currentWidth < 100) {
$('.progress-bar').css('background-color', 'red');
}
});

Fiddle

关于javascript - 如何根据元素的宽度改变背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17884979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com