gpt4 book ai didi

javascript - 如何制作一个像这样随着页面滚动超过某个点的导航栏?

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

如何使导航栏像下面这样,当用户向下滚动时,在某个点之后,导航栏会停留在左侧并随着用户向下滚动而滚动:

http://developer.android.com/design/get-started/ui-overview.html

理想情况下想知道是否有一个简单的 javascript 解决方案,或者 jquery 是否是首选方法。使用 div block 将不胜感激。我知道有position:relative;属性,但我不知道如何将它与 (javascript?) 一起使用,使其仅在用户向下滚动页面超过某个点后才会保留。

最佳答案

您可以通过检查元素进行大量挖掘。我看了一下导航,它的 iddevdoc-nav。如果您进入资源,他们有一个名为 doc.js 的 js 文件,其中包含以下代码:

  // Set up fixed navbar
var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
$(window).scroll(function(event) {
if ($('#side-nav').length == 0) return;
if (event.target.nodeName == "DIV") {
// Dump scroll event if the target is a DIV, because that means the event is coming
// from a scrollable div and so there's no need to make adjustments to our layout
return;
}
var scrollTop = $(window).scrollTop();
var headerHeight = $('#header').outerHeight();
var subheaderHeight = $('#nav-x').outerHeight();
var searchResultHeight = $('#searchResults').is(":visible") ?
$('#searchResults').outerHeight() : 0;
var totalHeaderHeight = headerHeight + subheaderHeight + searchResultHeight;
var navBarShouldBeFixed = scrollTop > totalHeaderHeight;

var scrollLeft = $(window).scrollLeft();
// When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
if (navBarIsFixed && (scrollLeft != prevScrollLeft)) {
updateSideNavPosition();
prevScrollLeft = scrollLeft;
}

// Don't continue if the header is sufficently far away
// (to avoid intensive resizing that slows scrolling)
if (navBarIsFixed && navBarShouldBeFixed) {
return;
}

if (navBarIsFixed != navBarShouldBeFixed) {
if (navBarShouldBeFixed) {
// make it fixed
var width = $('#devdoc-nav').width();
$('#devdoc-nav')
.addClass('fixed')
.css({'width':width+'px'})
.prependTo('#body-content');
// add neato "back to top" button
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});

// update the sidenaav position for side scrolling
updateSideNavPosition();
} else {
// make it static again
$('#devdoc-nav')
.removeClass('fixed')
.css({'width':'auto','margin':''})
.prependTo('#side-nav');
$('#devdoc-nav a.totop').hide();
}
navBarIsFixed = navBarShouldBeFixed;
}

resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
});


var navBarLeftPos;
if ($('#devdoc-nav').length) {
setNavBarLeftPos();
}

您不一定非要了解正在发生的一切,但我想向您展示的基本思想是,您所看到的一切都是通过 CSS 完成的。javascript 只是用来应用它在正确的时间使用 CSS。当用户滚动到某个点时,网页应用一个名为 fixed 的类(您可以在 default.css 中找到它)

  #devdoc-nav.fixed {
position: fixed;
margin:0;
top: 20px; }

是的,希望您能从这里得到一个想法。有很多方法可以做到这一点,但既然你展示了这个例子,我只是向你展示他们拥有的代码,也许你可以从中汲取一些东西。如果您需要帮助,请随时发表评论。

关于javascript - 如何制作一个像这样随着页面滚动超过某个点的导航栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925717/

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