2016-01-13 68 views
0

我有一個可滾動的下拉菜單,我想保持最後一項固定並始終可見,而所有其他項目將滾動。然而,用我的解決方案,它真的很蠢。這是我到目前爲止有:固定的菜單項

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

有沒有做到我想要一個簡單的方法去做?謝謝!

+0

你可以發表小提琴嗎? – pratikpawar

+0

我同意。一個jsfiddle會容易得多! –

+0

它似乎工作正常,有什麼問題? – Patareco

回答

0

我沒有,除了鉻的任何地方進行測試,但在這裏是你的問題的一個純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/

希望它你的原意。