拖拽效果

Posted Kevin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了拖拽效果相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>拖拽效果</title>
</head>
<style>
    body {
        background: skyblue;
    }
    #wrap {
        margin: 50px auto;
        width: 400px;
        height: 400px;
        border: 8px #b1b8e0 solid;
        background: #e9eff8;
        position: relative;
    }
    #drag {
        width: 50px;
        height: 50px;
        border: 8px #eb651d;
        background: #9de4ec;
        position: absolute;
        top: 0;
        left: 0;
    }
</style>
<body>
    <div id="wrap">
        <div id="drag"></div>
    </div>
    <!-- ================================================================================================================================= -->
    <script>
        var wrap = document.getElementById(\'wrap\');
        var drag = document.getElementById(\'drag\');

        drag.onmousedown = function(event){
            var event = event || window.event;//后者为IE
            //clientX获取鼠标距左窗口的距离
            //offsetLeft待移动对象的左外边距
            //tmpX作用在待移动对象上的鼠标到待移动对象左边距的距离
            var tmpX = event.clientX - drag.offsetLeft;
            var tmpY = event.clientY - drag.offsetTop;
            //取消默认行为
            if(event.preventDefault){
                event.preventDefault();
            }else{
                event.returnValue = false;
            }
            document.onmousemove = function(event){
                var event = event || window.event;
                //endX移动后对象的左边到左窗口的距离
                //clientWidth = width + padding
                //offsetWidth = width + padding + border
                //简单的说mouseX = 大框的宽度 -(小框的宽度+内外边距)
                var endX = event.clientX - tmpX;
                var endY = event.clientY - tmpY;
                var mouseX = wrap.clientWidth - drag.offsetWidth;
                var mouseY = wrap.clientHeight - drag.offsetHeight;

                if(endX >= mouseX){
                    endX = mouseX;
                }
                if(endX <= 0){
                    endX = 0;
                }
                if(endY >= mouseY){
                    endY = mouseY;
                }
                if(endY <= 0){
                    endY = 0;
                }
                drag.style.left = endX + \'px\';
                drag.style.top = endY + \'px\';
            }

        }
        //鼠标抬起时清空移动操作
        document.onmouseup = function(){
            document.onmousemove = null;
        }
    </script>
</body>
</html>

 

效果图:

以上是关于拖拽效果的主要内容,如果未能解决你的问题,请参考以下文章

android 自定义View:仿QQ拖拽效果

canvasn拖拽效果

angualr项目table拖拽列宽效果

简单的鼠标拖拽效果(原生js实现)

纯 CSS 也能实现拖拽效果?

原生弹窗拖拽代码demo+简单的抽奖