[英]convert jQuery to plain javascript code
i'm trying to replicate the navbar of this website , i have successfully implement it using jQuery but i need to rewrite this in plain javascript 我正在尝试复制此网站的导航栏,我已经使用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);
this is my attempt to rewrite it in plain JS but its not working atm 这是我尝试用普通的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);
};
}());
You are very close, first of, you probably want to remove the orginal #nav-2
since you are making a copy. 您非常亲密,首先,由于要进行复制,因此可能要删除原始的#nav-2
。 Second of, you want to determine the scrollTop of the body, which you access by document.body, see updates below: 其次,您要确定通过document.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);
};
}());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.