由於公司需要一個上傳圖片的組件然后有了這么些個需求:
1.圖片太多的時候需要滾動條滾動顯示
2.點擊上傳時需要遮罩避免觸發其他事件干擾
然而布局的時候會發現有幾個難點需要克服:
3.由於我的按鈕是通過相對定位配合絕對定位在底部固定的效果,在存在滾動條的情況下,會在滾動的時候按鈕會隨滾動條移動
4.(個人ui美化需求)想順便再隱藏一下滾動條
通過網上查的部分功能實現方法,現在整理一下思路吧
必要時顯示滾動條:
max-height + overflow: auto;
遮罩:
1.絕對定位+left、right、top、bottom: 0;可以遮住父元素;
2.絕對定位+left、top: 0;+width、height: 100%;也可以遮住父元素;
固定在底部:
父元素position: relative;子元素position: absolute;+子元素left\right\top\bottom: 0;可以固定在對應方向;
固定在底部+滾動條:
根據上面方法定位並在父級元素上直接添加滾動條樣式,定位就會出問題。網上找到的方案是在外部添加一個元素,相對定位移動到外部元素上,把按鈕定位在這個輔助的元素上如下圖
<div class="helper-wrap"> <div class="wrap1"> <div class="inner-wrap">內容</div> <div class="inner-btn"></div> </div> </div> <style> .helper-wrap{ position: relative; width: 300px; margin: auto; } .wrap1{ width: 100%; max-height: 200px; overflow: auto; } .inner-wrap{ position: relative; height: 1430px; padding: 10px; background-color: #096; } .inner-btn{ position: absolute; bottom: 0; left: 0; right: 0; height: 30px; background-color: rgba(0,0,0,.8); } </style>
所以滾動條隱藏確實有必要
網上有很多方法,需要添加元素進行布局,通過有滾動條的元素margin-right: -1em;+父元素width: fit-content;overflow: hidden;可以隱藏掉子元素的滾動條
還需要注意的是:
由於遮罩情況下還能滾動,所以遮罩的父元素應該是內容元素或者和內容等高的其父元素且應該是可滾動元素的內部元素(定位在子元素上會使得滾動條也被遮住)
大概整理個框架:
具體代碼如下:
<div class="helper-wrap"> <div class="wrap1"> <div class="inner-wrap"> <div class="content"> <div class="block"></div> <div class="block"></div> <div class="block"></div> <div class="block"></div> </div> <div class="mask"></div> </div> <div class="inner-btn"></div> </div> </div> <style> .helper-wrap{ position: relative; width: fit-content; border: 1px solid red; margin: auto; overflow: hidden; } .wrap1{ width: 300px; max-height: 600px; margin-right: -1em; overflow: auto; } .wrap1::-webkit-scrollbar { display: none; } .inner-wrap{ position: relative; } .content{ padding: 10px; background-color: #096; } .block{ width: 80px; height: 400px; padding: 10px; margin: 30px; background-color: #f5f5f5; } .mask{ position: absolute; left: 0; top: 0; bottom: 0; right: 0; /* width: 100%; height: 100%; */ background-color: rgba(0,0,0,.4); z-index: 8; } .inner-btn{ position: absolute; bottom: -30px; left: 30px; right: 30px; height: 30px; background-color: rgba(0,0,0,.8); z-index: 4; cursor: pointer; transition: .3s; } .wrap1:hover .inner-btn{ bottom: 0; } .wrap1:hover ~ .inner-btn{ bottom: 0; } </style>
具體效果:
歡迎各位大佬修正補充......