将jQuery转换为普通的javascript代码

时间:2017-06-15 07:45:22

标签: javascript jquery

我试图复制this website的导航栏,我已经使用jQuery成功实现了它,但我需要在普通的javascript中重写它

(function ($) {
$(document).ready(function () {
    var $nav1 = $("#nav-1"),
        $nav2 = $("#nav-2"),
        $sticky = $nav1.before($nav2.addClass("fixed").removeClass("hide"));

    $(window).on("scroll", function () {
        var fromTop = $(window).scrollTop();
        $("body").toggleClass("on-scroll", (fromTop > 200));
    });
});
})(jQuery);

这是我尝试在普通JS中重写它,但它没有工作atm

(function () {
var nav1 = document.getElementById("nav-1"),
    nav2 = document.getElementById("nav-2"),
    sticky = nav1.insertAdjacentHTML("beforebegin", nav2.outerHTML);

// nav2.className += " fixed";
nav2.classList.add("fixed");
nav2.classList.remove("hide");

window.onscroll = function () {
    var fromTop = window.scrollTop;
    body.classList.toggle("on-scroll", fromTop > 200);
};
}());

1 个答案:

答案 0 :(得分:0)

您非常接近,首先,您可能希望删除原始#nav-2,因为您正在制作副本。其次,您要确定body.body访问的正文的scrollTop,请参阅以下更新:

(function () {
var nav1 = document.getElementById("nav-1"),
    nav2 = document.getElementById("nav-2"),
    sticky = nav1.insertAdjacentHTML("beforebegin", nav2.outerHTML);

nav2.parentElement.removeChild(nav2);

// nav2.className += " fixed";
nav2.classList.add("fixed");
nav2.classList.remove("hide");

window.onscroll = function () {
    var fromTop = document.body.scrollTop;
    document.body.classList.toggle("on-scroll", fromTop > 200);
};
}());

JSFiddle