gpt4 book ai didi

javascript - 根据滚动位置更新选择菜单中的选定选项

转载 作者:太空宇宙 更新时间:2023-11-04 14:24:00 25 4
gpt4 key购买 nike

我有一种单页网站,它使用标准的 ul 菜单作为导航,然后在移动设备上使用选择菜单。我已经整理出如何根据可见/滚动到 div 设置“事件”菜单项,但我不确定如何更改事件选项以达到相同的效果。我在这里设置了一个 fiddle ,供您查看到目前为止我在哪里。代码也在下面

http://jsfiddle.net/e9XG5/3/

    // This function will be executed when the user scrolls the page.
$(window).scroll(function(e) {
// Get the position of the location where the scroller starts.
var scroller_anchor = $(".scroller_anchor").offset().top;

// Check if the user has scrolled and the current position is after the scroller's start location and if its not already fixed at the top
if ($(this).scrollTop() >= scroller_anchor && $('.scroller').css('position') != 'fixed')
{ // Change the CSS of the scroller to hilight it and fix it at the top of the screen.
$('.scroller').addClass('sloozis');
// Changing the height of the scroller anchor to that of scroller so that there is no change in the overall height of the page.
$('.scroller_anchor').css('height', '50px');
}
else if ($(this).scrollTop() < scroller_anchor && $('.scroller').css('position') != 'relative')
{ // If the user has scrolled back to the location above the scroller anchor place it back into the content.

// Change the height of the scroller anchor to 0 and now we will be adding the scroller back to the content.
$('.scroller_anchor').css('height', '0px');

// Change the CSS and put it back to its original position.
$('.scroller').removeClass('sloozis');
}
var lastId,
topMenu = $(".nav"),
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; }
});

// 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");
}
});

$(document).ready(function(e) {

$('#nav ul li a').bind('click', function(e) {
e.preventDefault();
$('html,body').animate({scrollTop: $(this.hash).offset().top});
});
});

最佳答案

修复:http://jsfiddle.net/x3MLa/

您没有更新所选选项,将类似这样的内容添加到您更新 anchor 的位置:

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

//added to update the correct option in the dropdown menu
$('option[value="#' + id + '"]').attr('selected','selected');
}

关于javascript - 根据滚动位置更新选择菜单中的选定选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19691318/

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