2017-06-15 140 views
0

我試圖複製的this website導航欄,我已經成功地使用jQuery實現它,但我需要在普通的JavaScriptjQuery的轉換爲純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); 
}; 
}()); 
+0

所以問題是什麼? – ZombieChowder

+1

爲什麼你想用純JS寫呢? – Raptor

回答

0

工作你是非常接近的,首先,你可能想要刪除的原單#nav-2,因爲你是一個副本。其次,你要確定身體的scrollTop的,您可以通過document.body的訪問,請參見下面的更新:

(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

+0

嘿謝謝你,現在工作:) – Mike