当菜单位于视口外部时触发事件,并将菜单固定在视口顶部

Fire event when menu is outside viewport and fix menu to top of viewport

本文关键字:视口 菜单 事件 顶部 于视口 单位 外部      更新时间:2023-09-26

我有一个menu元素,如果menu元素由于滚动而超出视口,我想将其固定在浏览器视口的顶部。从概念上讲,我的网页看起来像下面的示例 HTML,其中菜单位于标题中的一些文本下方。用户滚动过标题后,菜单应固定在浏览器视口的顶部,以便菜单始终可见。同样,如果用户向上滚动,菜单应返回到非固定位置,以便标题再次在浏览器视口中可见。

更新:设计要求是菜单应位于标题下方,因为它包含一些必须在菜单之前阅读的重要消息,只有当您滚动经过标题时,菜单才应固定在浏览器视口的顶部。

我猜我需要 JQuery 来完成这项工作?请有人发布一些例子。

<html>
<body>
<header id="header">Header text...
   <menu id="menu"><a href="/">Home</a> | <a href="/Help">Help</a></menu>
</header>
<section id="more">More text...</section>
</body>
</html> 

这只是通过jQuery完成的一个例子.只需在标题下方添加4 , 5个带有文本的段落,即可查看其工作原理。下面有一个通过代码笔的例子。

.HTML:

  <header>
      <div class="logo">STICKY MENU ON SCROLL!</div>
      <div class="intro">Some dumbass tagline goes here</div>
      <div class="menu">Menu goes here - home - links - blah blah</div>
    </header>

.CSS:

.logo {font-size:40px; font-weight:bold;color:#00a; font-style:italic;}
.intro {color:#777; font-style:italic; margin:10px 0;}
.menu {background:#00a; color:#fff; height:40px; line-height:40px;letter-spacing:1px; width:100%;}

.JS:

$('.menu').addClass('original').clone().insertAfter('.menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();
scrollIntervalID = setInterval(stickIt, 10);

function stickIt() {
  var orgElementPos = $('.original').offset();
  orgElementTop = orgElementPos.top;               
  if ($(window).scrollTop() >= (orgElementTop)) {
    // scrolled past the original position; now only show the cloned, sticky element.
    // Cloned element should always have same left position and width as original element.     
    orgElement = $('.original');
    coordsOrgElement = orgElement.offset();
    leftOrgElement = coordsOrgElement.left;  
    widthOrgElement = orgElement.css('width');
    $('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement).show();
    $('.original').css('visibility','hidden');
  } else {
    // not scrolled past the menu; only show the original menu.
    $('.cloned').hide();
    $('.original').css('visibility','visible');
  }
}

这是演示