如何使用 jQuery 将数字添加到当前 CSS 宽度

How to add number to current CSS width with jQuery

我正在研究一种会根据您做出的决定而上升或下降的仪表。

我通过将 CSS 的宽度百分比更改为 jQuery 来做到这一点。

目前我可以将它设置为任意百分比,但我想在当前值的基础上加上或减去一个百分比。

我该怎么做?

我的代码:

        $("#meter").css("width", "40%");
        $(".fan-percent").text("40%");

我的HTML:

<div id="fanHappiness">

<h4 class="white">Fan Happiness:</h4>

<div id="meter">

    <h4 class="white fan-percent">50%</h4>

</div>

谢谢。

更新:

使用这段代码我也得到了它的工作,但它只是从原始数字中减去或增加,所以如果我将 25 添加到原始 50,然后减去 25,我没有得到 50,我得到25. 也许在从 CSS 中检索数字后将其存储在变量中会有所帮助。

        $("#meter").width($("#meter").width() + 25);
        $(".fan-percent").text($(".fan-percent").width() + 25 + "%");

$("#meter").css("width") 将 return 百分比;因此,您可以根据“/”拆分 returned 值,然后 increment/decrement 分离出的数字。完成后,您可以更新 css 和文本。如果不清楚,请告诉我,and/or 你需要一些代码来可视化。

这应该可以解决问题:

$(document).ready(function () {
    var percent = "40%";  
    $("#meter").css("width", percent);
    $(".fan-percent").text(percent);
});

function addHappiness(){
    var currentPercent = $("#meter")[0].style.width.slice(0,-1);
    newpercent = +currentPercent + 10;
    $("#meter").css("width", newpercent + "%");
    $(".fan-percent").text(newpercent + "%");
}

JsFiddle: https://jsfiddle.net/dnyseaen/1/