gpt4 book ai didi

javascript - 使用 javascript 在菜单上显示事件状态

转载 作者:行者123 更新时间:2023-12-03 12:38:39 26 4
gpt4 key购买 nike

我这里有一个持久的黄色菜单:http://jsfiddle.net/KCb5z/11/

如您所见,它保留在页面上。我想要实现的目标是,一旦用户滚动到该部分,就将事件阶段放在菜单项上(即黄色菜单位于当前部分的顶部)

似乎有很多不同的方法可以尝试,但我真的不知道如何开始。 Bootstrap 在这里执行此操作(当您向下滚动时)http://getbootstrap.com/javascript/使用名为“scrollspy”的东西,但对于如此简单的东西来说,其代码似乎太大了:

// Cache selectors
var lastId,
topMenu = $("#top-menu"),
topMenuHeight = topMenu.outerHeight()+15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});

// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});

// Bind to scroll
$(window).scroll(function(){
// Get container scroll position
var fromTop = $(this).scrollTop()+topMenuHeight;

// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";

if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#"+id+"]").parent().addClass("active");
}
});

最佳答案

给你

 $(function () {

var $select = $('#select');
var $window = $(window);
var isFixed = false;
var init = $select.length ? $select.offset().top : 0;

$window.scroll(function () {
var currentScrollTop = $window.scrollTop();
if (currentScrollTop > init && isFixed === false) {
isFixed = true;
$select.css({
top: 0,
position: 'fixed'
});
$('body').css('padding-top', $select.height());
} else if (currentScrollTop <= init && isFixed === true) {
isFixed = false;
$select.css('position', 'relative');

$('body').css('padding-top', 0);
}
//active state in menu
$('.section').each(function(){
var eleDistance = $(this).offset().top;
if (currentScrollTop >= eleDistance) {
var makeActive = $(this).attr('id');
$('#select a').removeClass('active');
$('#select a.' + makeActive).addClass('active');
}
});
});

$(".nav").click(function (e) {
e.preventDefault();
var divId = $(this).attr('href');
$('body').animate({
scrollTop: $(divId).offset().top - $select.height()
}, 500);
});



});

check the fiddle here

关于javascript - 使用 javascript 在菜单上显示事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23610756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com