Javascript 粘性导航和jQuery
有点问题。希望构建一个粘性nav,当粘性nav触发时,添加'is sticky'类,我想向另一个div添加一个不同的类 下面是代码 谢谢Javascript 粘性导航和jQuery,javascript,php,jquery,html,css,Javascript,Php,Jquery,Html,Css,有点问题。希望构建一个粘性nav,当粘性nav触发时,添加'is sticky'类,我想向另一个div添加一个不同的类 下面是代码 谢谢 <script> $(document).ready(function(){ if ( $(".sticky-wrapper").hasClass("is-sticky") ) { $("#menu-item-25").css({display: "inline"}); } }); </script>
<script>
$(document).ready(function(){
if ( $(".sticky-wrapper").hasClass("is-sticky") ) {
$("#menu-item-25").css({display: "inline"});
}
});
</script>
$(文档).ready(函数(){
if($(“.sticky wrapper”).hasClass(“is sticky”)){
$(“#menu-item-25”).css({display:“inline”});
}
});
添加所需的类
$("#element").addClass('myclass');
您还可以使用删除类
$("#element").removeClass('myclass');
并使用
$("#element").toggleClass('myclass');
但是你的代码离粘粘的导航很远,我是这样做的
$(function() {
// grab the initial top offset of the navigation
var sticky_navigation_offset_top = $('nav').offset().top;
// our function that decides weather the navigation bar should have "fixed" css position or not.
var sticky_navigation = function(){
var scroll_top = $(window).scrollTop(); // our current vertical position from the top
// if we've scrolled more than the navigation, change its position to fixed to stick to top,
// otherwise change it back to relative
if (scroll_top > sticky_navigation_offset_top) {
$('nav').css({ 'position': 'fixed', 'top': '0px', 'left': '0px', 'line-height': '30px' });
} else {
$('nav').css({ 'position': 'relative', 'top': '0px' });
}
};
// run our function on load
sticky_navigation();
// and run it again every time you scroll
$(window).scroll(function() {
sticky_navigation();
});
});
很明显,您必须使用css,这里有很多我不确定的地方,但是: 您需要一个事件监听器,该监听器可以生成添加/删除所需类/css的代码。您现在拥有的是一个事件侦听器,但它正在侦听文档就绪状态,而不是触发粘性nav的滚动。因此:
<script>
$(document).ready(function(){
//add a listener for something that would indicate a sticky-state change, presumably scrolling
$(document).on('scroll', function() {
checkForStickyNav();
});
function checkForStickyNav() {
//look for sticky nav, and prevent running over and over
if ( $(".sticky-wrapper").hasClass("is-sticky") && !$(".otherStuff").hasClass("stickyfied") {
//do your stuff here; presumably changing CSS as appropriate
//make sure to add something along the lines of 'stickyfied' above, so that you don't keep re-adding the css on every scroll event
$("#menu-item-25").css({display: "inline"});
$('.otherStuff').addClass('stickyfied');
}
</script>
$(文档).ready(函数(){
//添加一个监听器,用于指示粘性状态更改(可能是滚动)
$(文档).on('scroll',function(){
checkForStickyNav();
});
函数checkForStickyNav(){
//寻找粘性导航,并防止反复运行
if($(“.sticky wrapper”).hasClass(“是粘滞的”)和&&!$(“.otherStuff”).hasClass(“粘滞的”){
//在这里完成您的工作;可能会根据需要更改CSS
//确保按照上面的“stickyfied”添加一些内容,这样就不会在每次滚动事件中都重新添加css
$(“#menu-item-25”).css({display:“inline”});
$('.otherStuff').addClass('stickyfied');
}
您能描述一下,哪些代码不起作用?我们需要更多的细节,因为这并不能真正解释您的要求,您是否有一些代码可以查看/测试?