javascript - 固定菜单项

标签 javascript css

我有一个可滚动的下拉菜单,我想保持最后一个元素固定并始终在顶部可见,而所有其他元素将滚动。但是,对于我的解决方案,它真的很紧张。这是我到目前为止所拥有的:

HTML:

<ul class="menu">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
  <li>Item 7</li>
  <li>Item 8</li>
  <li>Item 9</li>
  <li class="fixed">Item 10</li> <!-- this item will be fixed and always on top -->
</ul>

Javascript:

 this.$('.menu').on('scroll', function() {
      if (stickyItem = $('.fixed')) {

          //get the y position of the parent
          topHeight = stickyItem.parent().offset().top;
          //how far apart the sticky item should always be from the top of the bar
          heightDiff = stickyItem.parent().height() - stickyItem.height();
          if ((stickyItem.offset().top - topHeight) < heightDiff) {
            heightApply = heightDiff + ( heightDiff - (stickyItem.offset().top - stickyItem.parent().offset().top));
            stickyItem.css('top', (heightApply)+'px');
          }

        }
    });

CSS:

ul li.fixed {
    position: absolute;
    bottom: 0;
}

有没有更简单的方法来完成我想做的事情?谢谢!

最佳答案

除了 chrome,我没有在任何地方测试过,但这里有一个纯 CSS 解决方案来解决你的问题:

html,body{height:100%; margin:0; padding:0}

ul {margin: 0; padding:0; height:auto;
/*this padding bottom allows the penultimate element to be displayed*/
padding-bottom:39px}

ul li {padding:10px; background:#eee; color:#333; 
font-family:sans-serif; border-bottom:1px solid #CCC; }

ul li.fixed { /*you could also use the :last pseudo selector*/
    width:100%;
    position: fixed;
    bottom: 0;
    background:lightblue;
}

https://jsfiddle.net/patareco/kb99u78p/1/

希望它能如您所愿。

关于javascript - 固定菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34774430/

相关文章:

javascript - 为什么代码中的比较语句给出 false;

html - 当DIV没有足够的空间但保持DIV居中时,如何使滚动条出现?

javascript - 如何在 Windows 版 emacs 中将 jslint 作为 javascript 编译工具运行?

javascript - 如何将文本发送到某个地址(使用 Javascript)?

html - 如何在 AngularJS 的 ng-repeat 中动态添加文本框的 CSS

html - body 是内部 div 的父标签吗?

html - 文本对齐 : center; ignored for display: flex element?

html - 添加CSS类时如何强制Angular更新元素CSS

javascript - 如何将 Google Maps API 调用内部的数据设置为变量?

javascript - 在 jQuery 中组合复选框选择器以获得唯一结果