簡體   English   中英

如何保持 <li> 元素固定的頂部和底部 <ul> 滾動時的元素

[英]How to keep <li> elements fixed top and bottom of <ul> element when scrolling

我有一個固定高度的ul ,如果有太多滾動條的話,那就是li元素的動態數量。 您可以通過單擊選擇li元素。

我想要的是li元素,如果在上方滾動則固定在頂部,或者如果在其下方滾動則固定在底部,因此活動的li元素始終顯示,而其他li元素只是滾動到活動元素之上。

我做了一個傻瓜 我正在使用Angular,我不知道這是否可以使用CSS解決,或者我是否需要一個指令等。

HTML:

div class="parent">
 <div class="child1">
   <input ng-model="vm.query" type="text" placeholder="Search" />
    <ul  >
        <li ng-repeat="todo in  todos" ng-class="{'active': todo.active}" ng-click="activeTodo($index)">
            <a>{{todo.name}}</a>
        </li>

    </ul>
 </div>

CSS:

.parent{
   display: flex;
}
.child1{

  background-color: #eeeeee;
  height: 500px;
  overflow:scroll;
}
.active{
 background-color: red;
 position:fixed;
}

提前致謝!

我使用一些CSS並制定指令來管理它。

在這里做了一個plu ..

我做了一個每個li元素得到的指令。 然后在指令中使用jquery,我得到必要的元素,比如div ,它有滾動,當前的li元素等。

兩個布爾值用於檢查li是固定在頂部還是底部。 然后檢查當前的scrollPosition(scrollTop)是否高於或低於當前的li元素。 它也檢查所以li元素也附加了活動布爾值。

return {
        restrict: 'A',

        link: function($scope, element, attributes){

            var scrollDiv = $('#scrollDiv'),
                liElement = element,
                liElementTop = parseInt(liElement.offset().top),
                scrollDivTop = parseInt(scrollDiv.offset().top),
                isFixedTop = false,
                isFixedBottom = false;

            liElement.width(scrollDiv.width());


            scrollDiv.on('scroll', function(){
                var scrollTop = scrollDiv.scrollTop();

                if (!isFixedBottom && !isFixedTop && scrollTop <= liElementTop - (scrollDivTop+(scrollDiv.height()-liElement.height())) && liElement.hasClass("active")) {
                    isFixedBottom = true;
                    liElement.css({'position': 'fixed', 'top': scrollDivTop+(scrollDiv.height()-liElement.height()+1),'list-style-type':'none','z-index':'10'});
                } else if (isFixedBottom && !isFixedTop && scrollTop >= liElementTop - (scrollDivTop+(scrollDiv.height()-liElement.height()))) {
                    isFixedBottom = false;
                    liElement.css({'position': 'static', 'top': 0});
                }
                else if (!isFixedTop && !isFixedBottom && scrollTop >= liElementTop - scrollDivTop && liElement.hasClass("active")) {
                    isFixedTop = true;
                    liElement.css({'position': 'fixed', 'top': scrollDivTop,'list-style-type':'none','z-index':'10'});
                }
                else if (isFixedTop && !isFixedBottom && scrollTop <= liElementTop - scrollDivTop) {
                    isFixedTop = false;
                    liElement.css({'position': 'static', 'top': 0});
                }

            })



        }
    };

如果我理解你正確,你喜歡頂部的活躍div。

在css中解決這個問題

使用position:relative parent和parent的position:absolute子元素的position:absolutetop:0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM