天天看點

最簡潔的js滑鼠拖曳效果【原】

請原諒我是一個标題檔,不過還是很簡潔的,因為隻是初步的實作的拖曳效果

<!DOCTYPE html>

<html>

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <meta http-equiv="Content-Language" content="zh-cn" />

    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

    <title>DragDrop</title>

    <meta name="author" content="flowerszhong">

    <meta name="date" content="">

    <link href="" rel="stylesheet" type="text/css" />

    <!--[if IE]>

      <script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>

  <![endif]-->

    <!-- <script src="http://code.jquery.com/jquery-latest.js"></script> -->

    <style type="text/css">

        .redBorderBox

        {

            border: 2px solid red;

            position: absolute;

            width: 60px;

            height: 60px;

            cursor: move;

            background-color: Red;

        }

    </style>

</head>

<body>

    <div id="hd">

    </div>

    <div id="bd">

        <div class="redBorderBox" id="dragObj1">

            i am not dragObj</div>

        <div class="redBorderBox dragObj" id="dragObj2" style="top: 90px; left: 90px;">

            u can drag me</div>

    <div id="ft">

</body>

<script>

    /* 滑鼠拖動 */

    (function() {

        var oDrag = "";

        var ox, oy, nx, ny, dy, dx;

        function drag(e) {

            var e = e ? e : event;

            oDrag = e.target ? e.target : e.srcElement;

            if (oDrag.className.indexOf("dragObj") == -1) { oDrag = ""}

            ox = e.clientX;

            oy = e.clientY;

        function dragPro(e) {

            if (oDrag != "") {

                var e = e ? e : event;

                dx = parseInt(oDrag.style.left);

                dy = parseInt(oDrag.style.top);

                nx = e.clientX;

                ny = e.clientY;

                oDrag.style.left = (dx + (nx - ox)) + "px";

                oDrag.style.top = (dy + (ny - oy)) + "px";

                ox = nx;

                oy = ny;

            }

        document.onmousedown = function(e) { drag(e); }

        document.onmouseup = function() { oDrag = ""; }

        document.onmousemove = function(event) { dragPro(event); }

    })();

</script>

</html>

感謝你留言,轉載請聲明出處:http://www.cnblogs.com/flowerszhong

繼續閱讀