jQuery .find() and .animate()

jQuery .find() and .animate()

本文关键字:animate and find jQuery      更新时间:2023-09-26

我正在做一个温度计,我正在做温度计的动画。我有这个javascript方法来做到这一点:

function setScoreBar(score) {
    var scoreBar = document.getElementById("dynamicScoreBar");
    // var scoreBar = $(scoreBarElem);
    var height = 250;
    height = height - 20;
    var percentage = height / 100;
    scoreBar.find(".meter").animate({
         marginTop: (height - (score * percentage)) + "px"
    }, 400, function() {
        scoreBar.find(".meter").html(score + "%");
    });
}

我的 html 看起来像这样

<div id="dynamicScoreBar" class="scoreBar">
    <div class="meter">0%</div>
    <div class="red"></div>
</div>

当我调试它时,我收到错误,指出 .find 和 .animate 方法不存在。但是当我尝试编写它时,我从视觉工作室获得了帮助,它向我展示了使用它的选项,所以它应该存在:P我可以使用其他东西吗?还是我有任何语法错误?

.find.animate是jQuery函数。当scoreBar是jQuery对象时,它们就存在。不是当你用document.getElementById分配它时。 getElementById是一个纯javascript函数,将返回一个DOM节点。

如果你使用的是jQuery框架,你可以通过用$(...)包装任何DOM节点来将它变成jQuery对象。对于您的特定方案,您可以完全重写变量赋值:

var scoreBar = $('#dynamicScoreBar');

scoreBar变量将是一个 jQuery 对象,具有可用的 findanimate 函数。