【问题标题】:Fire event when menu is outside viewport and fix menu to top of viewport当菜单在视口之外时触发事件并将菜单固定到视口顶部
【发布时间】:2016-01-23 15:44:24
【问题描述】:

我有一个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> 

【问题讨论】:

  • 可以包括css,js在问题上试过吗?
  • @guest271314 还没有尝试过任何东西,因为我还没有找到解决方案。这不是我面临的错误,而是如何从概念上解决手头的问题。谢谢。

标签: javascript jquery html css


【解决方案1】:

这只是一个如何通过 jQuery 完成的示例。只需在标题下方添加 4 、 5 个带有文本的段落,看看它是如何工作的。 下面有一个通过codepen的例子。

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');
  }
}

HERE IS THE DEMO

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 2014-03-03
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多