【问题标题】:How can I convert this jquery methods - .text(), .height() and .css() to vanilla javascript?如何将此 jquery 方法 - .text()、.height() 和 .css() 转换为 vanilla javascript?
【发布时间】:2021-12-18 19:46:27
【问题描述】:

您好,希望您今天过得愉快,

今天我决定在空闲时间尝试从 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();

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

【问题讨论】:

标签: javascript jquery function ecmascript-6 jquery-selectors


【解决方案1】:

我想这就是你需要的

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

小码sn-phere 但是,考虑到不良做法,sn-p 存在多个问题。

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

【讨论】:

  • 不要忘记document.querySelector 只返回第一个匹配项。如果需要更多,请考虑使用document.querySelectorAll
  • 已经提到@ManuelRomeiro
  • 确实如此。很抱歉没有仔细阅读那部分。
  • @sc0rp1on 谢谢你好先生
猜你喜欢
  • 2021-09-25
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 2011-03-30
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
相关资源
最近更新 更多