原生js鼠标拖拽div左右滑动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery.min.js"></script>
    <style>
        body{
            position: relative;
            margin:0;
            padding:0;
            width:100%;
            height: 1000px;
        }
        #box{
            height: 50px;
            width:200px;
            position: absolute;
            left:50%;
            top:50%;
            margin-left:-200px;
            margin-top:-200px;
            background: #CDCDCD;
        }
        #small-box{
            height: 50px;
            width:50px;
            position: absolute;
            left:0;
            top:0;
            background: #FF66CC;
            cursor:move ;
            opacity: 0.7;
        }
    </style>
</head>
<body>
    <div id="box">
        <div id="small-box"></div>
    </div>
<script>
    var box=$("#small-box");
    var body=$('body');
    var index=0;
    var x1;
    box.mousedown(function(){
        index=1;              //鼠标按下才能触发onmousemove方法
        var x=event.clientX;     //鼠标点击的坐标值,x
        var left= this.style.left;
        left=left.substr(0,left.length-2);   //去掉px
        x1=parseInt(x-left);
    });
    box.mousemove(function(){
        if(index===1){
            this.style.left=event.clientX-x1+'px';
            if(this.style.left.substr(0,this.style.left.length-2)<0){
                this.style.left=0;
            };
            if(this.style.left.substr(0,this.style.left.length-2)>150){
                this.style.left='150px';
            };
        }
    });
    box.mouseup(function(){
        index=0;
    });
    body.mouseup(function(){
        index=0;
    });
</script>
</body>
</html>

 

发布了28 篇原创文章 · 获赞 14 · 访问量 4万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览