我正在创建一个带有粘性导航的页面,并且在标题图像移开后它不会立即粘到顶部(它小于整页尺寸)。它仅在一整页图像的大小过去后才会粘住。导航栏内的文本也会在粘贴后移动。
您可以在此处查看代码:https://jsfiddle.net/zinctan/7a436ojz/
这是我的javascript:
$(function() {
// when we scroll down the window, do this:
$(window).scroll(function(){
//Getting the scroll percentage
var windowHeight = $(window).height();
var scrollHeight = $(window).scrollTop();
var scrollPercentage = (scrollHeight / windowHeight);
console.log(scrollPercentage);
// if we have scrolled past 200, add the alternate class to nav bar
if(scrollPercentage > 1) {
$('.navHighlighter').addClass('scrolling');
} else {
$('.navHighlighter').removeClass('scrolling');
}
});
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 80
}, 1000);
return false;
}
}
}); // code courtesy of CSS-Tricks
// apply the class of nav-active to the current nav link
$('a').on('click', function(e) {
e.preventDefault();
$('li.nav-active').removeClass('nav-active');
$(this).parent('li').addClass('nav-active');
});
// get an array of 'href' of each a tag
var navLink = $('ul.navHighlighter a');
console.log(navLink);
var aArray = [];
for(var i = 0; i < navLink.length; i++) {
console.log(i);
var aChild = navLink[i];
var navArray = $(aChild).attr('href');
console.log(navArray);
aArray.push(navArray);
console.log(aArray);
var selector = aArray.join(" , ");
console.log(selector);
}
$(window).scroll(function(){
var scrollTop = $(window).scrollTop();
var tops = [];
$(selector).each(function(){
var top = $(this).position().top - 90;
if(scrollTop > top) {
var id = $(this).attr('id');
$('.nav-active').removeClass('nav-active');
$('a[href="#'+id+'"]').parent().addClass('nav-active');
}
tops.push(top);
});
});
});
任何帮助都会有用!谢谢:))
答案 0 :(得分:0)
首先,使用它是一个好习惯:
$(document).ready(function(){
});
然后在该函数中编写jQuery代码,以确保在html网页完全加载后运行脚本代码。
现在,我认为这应该有效:
$(document).ready(function() {
var topDist = $(".navHighlighter").position(); //save the position of your navbar, better use an id for that
$(document).scroll(function () {
var scroll = $(this).scrollTop();
if (scroll > topDist.top) { //when the scrolling reaches the very top of your navbar
$('.navHighlighter').addClass('scrolling');
} else {
$('.navHighlighter').removeClass('scrolling');
}
});
*rest of your code goes here*
});
另外,添加:
top:0;
width: 100%;
到您的.scrolling类,以便命令您的导航栏从用户窗口的顶部开始,并覆盖整个网页的宽度(位置:已修复会产生一些问题,因此您有要设置元素的宽度,请记住)。
我希望我能帮到你,我的要求是正确的。快乐的编码! :)