css實現圖片滾動

<div class="box">
    <img src="images/1.gif" />
    <img src="images/2.gif" />
    <img src="images/3.gif" />
    <img src="images/4.gif" />
    <img src="images/5.gif" />
    <img src="images/6.gif" />
    <img src="images/7.gif" />
    <img src="images/8.gif" />
    <img src="images/9.gif" />
</div>
.box {
    width: 440px;
    white-space: nowrap;
    overflow: auto;
    scroll-snap-type: x mandatory;
}
.box img {
    scroll-snap-align: start;
}

從以上代碼,已經可以:當滑動滾動條時,滑到下一張圖片的一丟丟,就會平滑定位到下一張圖片了

scroll-snap-type

作用就是確定是水平滾動定位,還是垂直滾動定位。

none 默認值。表示滾動時候忽略捕捉點,也就是我們平時使用的滾動。

x 捕捉水平定位點。

y 捕捉垂直平定位點。

block 捕捉和塊狀元素排列一個滾動方向的定位點。默認文檔流下指的就是垂直軸。

inline 捕捉和內聯元素排列一個滾動方向的定位點。默認文檔流下指的就是水平軸。

both 橫軸縱軸都捕捉。

mandatory 表示“強制”,可選參數。強制定位,無論是添加刪除元素,或者滾動窗口較小,不足以放下子元素。

proximity proximity表示“大約”,可選參數。可能會定位。這個值的作用表現比較玄乎,時間有限,我也沒有弄透。大家可以對比下面這個demo,感受和mandatory屬性值的不同。

mandatory和proximity對比demo

scroll-snap-align

作用在滾動容器子元素上的,表示捕獲點是上邊緣,下邊緣,還是中間位置。

none 默認值。不定義位置。

start 起始位置對齊,例如,垂直滾動,子元素和容器同上邊緣對齊。

end 結束位置對齊,例如,垂直滾動,子元素和容器同下邊緣對齊。

center 居中對齊。子元素中心和滾動容器中心一致。

想要個輪播圖怎麼辦???想要有小圓點 不想要滾動條

scroll-behavior 平滑定位到指定元素的指定位置,跳轉不會太生硬

不結合js,能想到的就是錨點跳轉

<div class="box_wrap">
    <div class="box">
        <img src="images/1.gif" id="img1" />
        <img src="images/2.gif" id="img2" />
        <img src="images/3.gif" id="img3" />
        <img src="images/4.gif" id="img4" />
        <img src="images/5.gif" id="img5" />
        <img src="images/6.gif" id="img6" />
        <img src="images/7.gif" id="img7" />
        <img src="images/8.gif" id="img8" />
        <img src="images/9.gif" id="img9" />
    </div>
    <div class="circle">
        <a href="#img1" />
        <a href="#img2" />
        <a href="#img3" />
        <a href="#img4" />
        <a href="#img5" />
        <a href="#img6" />
        <a href="#img7" />
        <a href="#img8" />
        <a href="#img9" />
    </div>
</div>

.box_wrap {
    position: relative;
    width: 440px;
}
.box {
    width: 440px;
    white-space: nowrap;
    overflow: scroll;
    scroll-snap-type: x mandatory;
    scroll-behavior: smooth;
}
.box img {
    scroll-snap-align: start;
}
.circle {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 20px;
    text-align: center;
}
.circle a { /* 小圓點 */
    display: inline-block;
    width: 14px;
    height: 14px;
    background-color: red;
    border-radius: 50%;
    margin: 10px;
}
::-webkit-scrollbar {
    display: none; /* 隱藏滾動條 */
}

已經可以切換和滾動了

查看具體autosmooth例子

剩下的按鈕顏色需要配合js,今天的快樂就止於此吧

參考文章
1、大俠,請留步,要不過來了解下CSS Scroll Snap?
2、不可思議,純 css 都能圖片滾動
3、 scroll-snap-type

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章