有点问题。希望构建一个粘性导航,当粘性导航触发时,添加“粘性”'我想在另一个div中添加另一个类。
以下是代码..
谢谢
<script>
$(document).ready(function(){
if ( $(".sticky-wrapper").hasClass("is-sticky") ) {
$("#menu-item-25").css({display: "inline"});
}
});
</script>
答案 0 :(得分:0)
添加您需要的课程
$("#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
答案 1 :(得分:0)
这里有很多我不确定的事情,但是:
您需要一个事件监听器,它会导致添加/删除所需类/ css的代码。你现在拥有的是一个事件监听器,但它正在监听文档就绪状态,而不是一个触发粘性导航的滚动。所以:
<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>