拖动无jQuery UI的(draggable without jQuery ui)

2019-07-29 19:46发布

如何使不使用jQuery UI a元素可拖动?

我有这样的代码:

<script type="text/javascript">
    function show_coords(event)
    {
        var x=event.clientX;
        var y=event.clientY;
        var drag=document.getElementById('drag');
        drag.style.left=x;
        drag.style.top=y
    }
</script>

<body style="height:100%;width:100%" onmousemove="show_coords(event)">
     <p id="drag" style="position:absolute">drag me</p>
</body>

问题是,我想拖,而用户在按下鼠标按钮。 我试图onmousedown ,但结果均为阴性。

Answer 1:

当你的概念这将是很容易的。

function enableDragging(ele) {
    var dragging = dragging || false,        //Setup a bunch of variables
        x, y, Ox, Oy,
        enableDragging.z = enableDragging.z || 1,
        current;
    ele.onmousedown = function(ev) {         //When mouse is down
        current = ev.target;
        dragging = true;                     //It is dragging time
        x = ev.clientX;                      //Get mouse X and Y and store it
        y = ev.clientY;                      // for later use.
        Ox = current.offsetLeft;             //Get element's position
        Oy = current.offsetTop;
        current.style.zIndex = ++enableDragging.z;  //z-index thing

        window.onmousemove = function(ev) {
            if (dragging == true) {                //when it is dragging
                var Sx = ev.clientX - x + Ox,      //Add the difference between
                    Sy = ev.clientY - y + Oy;      // 2 mouse position to the
                current.style.top = Sy + "px";     // element.
                current.style.left = Sx + "px";
                return false;                      //Don't care about this.
            }
        };
        window.onmouseup = function(ev) {
            dragging && (dragging = false);        //Mouse up, dragging done!
        }
    };
}

enableDragging(document.getElementById("drag"));  //draggable now!

var ele = document.getElementsByTagName("div");
for(var i = 0; i < ele.length; i++){              //Every div's is draggable
    enableDragging(ele[i]);                       // (only when its "position"
}                                                 //  is set to "absolute" or
                                                  //  "relative")

http://jsfiddle.net/DerekL/NWU9G/

为什么你的代码是不工作的原因是因为<div>将始终遵循光标所在去,你实际上并没有它。 左上角会一直跟着你的光标,而这并不是我们想要的。


UPDATE

现在,如果你只想要一个抓取器或类似的东西,只是改变了这部分脚本:

ele.onmousedown = function(ev) {
    current = ev.target;

var grabber = document.createElement("div");
grabber.setAttribute("class", "grabber");
ele.appendChild(grabber);
grabber.onmousedown = function(ev) {
    current = ev.target.parentNode;

现在,你只能点击采集开始拖动过程​​。

http://jsfiddle.net/DerekL/NWU9G/7/



文章来源: draggable without jQuery ui