问题
I want to wrap my navigation and sub navigation in a div that becomes fixed once the user scrolls past the top. I'm using _s starter theme. My theme is called test.
Here is my nav code along with the wrapper (I don't have the subnav in, since I'm trying to figure this out first):
<div id='fixed-nav'>
<nav id="site-navigation" class="main-navigation" role="navigation">
<h1 class="menu-toggle"><?php _e( 'Menu', 'test' ); ?></h1>
<div class="skip-link"><a class="screen-reader-text" href="#content"><?php _e( 'Skip to content', 'test' ); ?></a></div>
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
</nav><!-- #site-navigation -->
Here is my css:
#fixed-nav {
border: 0;
background-color: #202020;
border-radius: 0px;
margin-bottom: 0;
height: 30px;
}
.navbar-fixed {
top: 0;
z-index: 100;
position: fixed;
width: 100%;
}
Here's my function.php:
function test_fixed_navigation() {
wp_enqueue_script( 'fixed-navigation', get_template_directory_uri() . '/js/fixed- navigation.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'test_fixed_navigation' );
And here's my fixed-navigation file:
( function() {
$(document).ready(function() {
$(window).scroll(function () {
//if you hard code, then use console
//.log to determine when you want the
//nav bar to stick.
console.log($(window).scrollTop())
if ($(window).scrollTop() > 280) {
$('#fixed-nav').addClass('navbar-fixed');
}
if ($(window).scrollTop() < 281) {
$('#fixed-nav').removeClass('navbar-fixed');
}
});
});
If someone could please point out what I've done wrong. It simply keeps scrolling and doesn't become fixed.
Edit: I'm using this:
http://jsfiddle.net/CriddleCraddle/Wj9dD/
回答1:
So I'm not 100% sure I understand what you want, or what is not working for you. But if you want the nav_bar
to keep in place at the top as you scroll down you have that working..
Did you want the nav_bar
to start out at the top?
Here is an example I changed the html to make it more obvious what was going on.
<div id="banner">
<h2>put what you want here</h2>
<p>just adjust javascript size to match this window</p>
</div>
<nav id='nav_bar'>
<ul class='nav_links'>
<li><a href="url">Nav Bar</a></li>
<li><a href="url">Sign In</a></li>
<li><a href="url">Blog</a></li>
<li><a href="url">About</a></li>
</ul>
</nav>
<div id='body_div'>
<p style='margin: 0; padding-top: 50px;'>and more stuff to continue scrolling here </p>
<br>
<br>
<br>
<br>
<p>more stuff</p>
<br>
<br>
<br>
<br>
<p>and more..</p>
</div>
http://jsfiddle.net/Wj9dD/13/
来源:https://stackoverflow.com/questions/19328107/fixed-navigation-on-scroll