【问题标题】:How to select an element based on a style value?如何根据样式值选择元素?
【发布时间】:2019-10-15 04:37:55
【问题描述】:

我正在制作一个自定义进度条,我想根据它的 width 值更改颜色。即如果width 小于 50%,则条为红色,如果大于则条为绿色。

我知道我可以像这样使用属性选择器:

.p-bar[style*="width: 10"] {
    background-color: red;
}

但是这样做意味着我必须在每一步都分配一个值......

P.D. sass 解决方案可以接受,谢谢。

编辑

P.P.D. js 解决方案也可以接受......但我想知道是否有办法用 CSS 完成我想要的。

【问题讨论】:

  • 除非style 在 HTML 中... 你不能
  • 哦...这令人沮丧。好吧,我只是很难有一种方法可以使“10”成为变量或其他东西。我想我会要求一个js解决方案,那也很好。顺便说一句,谢谢您的回答。
  • 使进度条发生变化的 HTML/ 代码是什么?
  • 再添加一些代码会更容易提供帮助

标签: javascript jquery html css sass


【解决方案1】:

好的...正如之前所说,似乎不可能只使用 css 来做我想做的事情。 但是,使用 javascript 根据值更改颜色似乎很容易。

这是我最终使用的代码(我有一个按钮可以将 10% 的“进度”AKA width 添加到我的栏):

var progressed = 0; /* Variable to handle the width % */
$('.btnAddProgress').click(function(){
    var progressBar = $(this).parent().find('.progress-bar'); /* Get the bar */
    progressed += 10;
    progressBar.css({
        'width': progressed + '%', /* Apply the changed width */
    });

var progPrcnt = progressBar.width() / progressBar.parent().width() * 100; /* Wanted to get the actual element width because I figured I would not always have a variable like my "progressed" which value matches the actual width */
if (progPrcnt < 50) {
    progressBar.css({
        'background-color': '#f00',
    });
} else {
    progressBar.css({
        'background-color': '#0f0',
    });
}
});

无论如何...事实证明,使用 JS 做我想做的事情相当容易,并且很快就弄清楚了,然后 不想 忘记回到我的帖子并指出我有多愚蠢。

无论如何,我总是说我还在学习,非常感谢您的耐心帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 2021-04-30
    • 1970-01-01
    • 2011-01-04
    • 2021-10-20
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多