jQuery內容橫向拖拽滾動

你怕黑暗麼發表於2018-07-07

如果有業務需求:使用橫向滾動,而又不想用滾動條,可以使用橫向拖拽滾動,主要是利用元素的scrollLeft特性;

廢話不多說直接上程式碼;

css:

.box{
        width:100%;
        height:30px;
        line-height:30px;
        overflow:hidden;
    }
    .box-container{
        cursor: move;
        white-space:nowrap;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }
    .box-container a.mumber {
        text-decoration:none;
        color:#333;
        padding:0 0 0 20px;
    }

html結構:

<div class="box">
    <div class="box-container">
        <a  class="mumber">person1</a>
        <a class="mumber">person2</a>
        <a class="mumber">person3</a>
        <a class="mumber">person5</a>
        <a class="mumber">person6</a>
        <a class="mumber">person7</a>
        <a class="mumber">person8</a>
        <a class="mumber">person9</a>
        <a class="mumber">person10</a>
        <a class="mumber">person11</a>
        <a class="mumber">person12</a>
        <a class="mumber">person13</a>
        <a class="mumber">person14</a>
        <a class="mumber">person15</a>
        <a class="mumber">person16</a>
        <a class="mumber">person17</a>
        <a class="mumber">person18</a>
        <a class="mumber">person19</a>
        <a class="mumber">person20</a>
        <a class="mumber">person21</a>
        <a class="mumber">person22</a>
    </div>
</div>  

jquery程式碼  

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
    $(function(){
        var boxContainer = $('.box .box-container'),
            box = $('.box'),
            boxWidth = box.width(),
            mumber = boxContainer.find('a.mumber'),
            mumberWidth = mumber.width()+20,
            length = mumber.length,
            boxContainerWidth = mumberWidth*length;
        boxContainer.css('width',boxContainerWidth);
        //當外容器寬度大於內部容器寬度,直接返回
        if(parseInt(boxWidth)>=parseInt(boxContainerWidth))return false;
        boxContainer.on('mousedown',function(e){
            var posX = e.screenX;//滑鼠點選時候的位置
            $(document).on('mousemove',function(e){
                var posL = e.clientX,//滾動後滑鼠的位置
                    moveX = posL -posX,//滑鼠拖動距離
                    currentScroll = box.scrollLeft();//當前的scrollLeft值
                currentScroll += moveX;
                box.scrollLeft( currentScroll)
            })
            //清空事件
            $(document).on('mouseup',function(){
                $(this).unbind();
            })
        })
    })

</script>

  

相關文章