html制作水平滚动容器

  如上图所示,制作一个这样的水平容器,用来在点击的时候左右滑动元素,html代码如下,

<div style="display: flex;justify-content: space-between;background-color: #2D3653;">

    <div @click="left" style="
                              padding: 0 10px;display: flex;align-items: center;border-radius: 10px 0 0 10px;">
        <span style="color:#fff;font-size:20px;font-weight:bold;">&lt;</span>
    </div>

    <!--滑动区域-->
    <div class="div01">

        <div class="div02" ref="scollView">
            <div class="houseContainer">
                <div class="divOut" v-for="(item,index) in datas" :key="index" @click="chooseHouse(item,index)">
                    <img :src="require('@/assets/leatherFactory/p7.png')" alt=""
                         style="" class="img1" />


                    <div style="" class="divRight">
                        <label style="" class="label1">{{item.name}}</label>
                        <div style="" class="divMiddle">
                            <label style="" class="label2">{{item.value}}</label>
                            <label style="" class="label3">千克</label>
                        </div>
                    </div>

                </div>
            </div>


        </div>

    </div>



    <div @click="right" style="
                               padding: 0 10px;display: flex;align-items: center;border-radius: 10px 0 0 10px;">
        <span style="color:#fff;font-size:20px;font-weight:bold;">></span>
    </div>

</div>

  上述代码还不能实现图片效果,需要CSS,最主要是div01,div02和houseContainer的CSS, 

.div01{
    overflow: hidden;
    flex:1
}
.div02{
    position: relative;
    overflow-x: scroll; //让元素可以X轴滚动,如果是Hidden,则无法滚动
}
.div02::-webkit-scrollbar { //此处主要是为了去除chrome中展示滚动条,其他浏览器无效
    display: none; 
}

.houseContainer{
    display: flex;
    position: relative;
    align-items: center;
}

.divOut{
    border-radius: 10px;
    text-align: center;
    display: flex;
    justify-content: center;
    background-color: #7A6FF0;
    margin-right: 10px;
    position: relative;
    // opacity: 0.5;

    text-align: center;
    flex: 1;
    min-width: 19rem;

}

  接下来就是添加左右的点击事件,

left(){
    let offset = this.$refs.scollView.scrollLeft
    this.$refs.scollView.scroll({
        left: offset - 200,
            behavior: 'smooth'
    })
},
right(){
    let offset = this.$refs.scollView.scrollLeft
    this.$refs.scollView.scroll({
        left: offset + 200,
            behavior: 'smooth'
    })
}

 

posted @ 2023-02-09 17:50  伟衙内  阅读(106)  评论(0编辑  收藏  举报