首页 > 解决方案 > 如何将此 jquery 方法 - .text()、.height() 和 .css() 转换为 vanilla javascript?

问题描述

嗨,我希望你有一个美好的一天,

今天我决定在空闲时间尝试从 jquery 转换为 vanilla javascript,但我已经工作了几个小时的代码,我真的很难将这段代码从 Jquery 转换为 vanilla javascript。

我想更改的代码

$("h1").text(Math.round(progress) + "%").css({ color: textColor });    
$(".fill").height(progress + "%").css({ backgroundColor: bgColor });

完整代码:

function progress() {
    var windowScrollTop = $(window).scrollTop();
    var docHeight = $(document).height();
    var windowHeight = $(window).height();
    var progress = (windowScrollTop / (docHeight - windowHeight)) * 100;

    var bgColor = progress > 99 ? "#fff" : "#fff";
    var textColor = progress > 99 ? "#fff" : "#333";

    $("h1").text(Math.round(progress) + "%").css({ color: textColor });

    $(".fill").height(progress + "%").css({ backgroundColor: bgColor });
}

progress();

我真的很抱歉所有的麻烦我希望你能帮助我解决我的问题。谢谢你。

标签: javascriptjqueryfunctionecmascript-6jquery-selectors

解决方案


我认为这就是你需要的

document.querySelector("h1").innerText = Math.round(progress) + "%"
document.querySelector("h1").style.color = textColor
document.querySelector(".fill").style.height = progress + "%"
document.querySelector(".fill").style.backgroundColor = bgColor

此处的小代码片段 但是,考虑到不良做法,该片段存在多个问题。

您应该使用类附加 CSS(对 iOS 有帮助)。此外,如果您想将其放在具有相同类名/标签名的多个元素上,请考虑使用带有循环的 querySelectorAll。


推荐阅读