拖动'放置元素定位

时间:2017-07-09 07:57:33

标签: javascript html drag-and-drop targeting

所以我正在编程(和朋友一起)一个Drag'n Drop系统,其中包含用于HTML的HTML元素(这里是按钮)。然后我意识到,如果我在这个页面上有多个元素怎么办?答:所有这些都受到影响。所以我说......好吧!我只是越来越多地为id添加一个值,然后整个事情就不会干涉。

所以现在我遇到了问题,我无法知道哪个元素被定位......或更好:哪个ID被定位。

PS:请JS只有JQuery,没有框架。

PPS :(我已经通过Stackoverflow等查看了这种情况,没有什么非常适合我的情况,至少我没找到一个)

    var pressed = 0;

    function drag(state){
        if(state == true){
           pressed = 1;
        }
        else{
           pressed = 0;
        }
    }
  var obj = "";
    onmousemove = function(a){
        if(pressed == 1){
    obj = document.getElementById("move1"); //<-- This var (obj) needs to be "flexible" to any element, not only the element with the id "move1"
            var x = a.clientX - parseInt(obj.style.width) / 2;
            var y = a.clientY - parseInt(obj.style.height) / 2;
            obj.style.left = x + "px";
            obj.style.top = y + "px";
        }
    }

var counter = 0;

function createbutton() {
counter++;
document.getElementById("surface").innerHTML += "<button id = 'move" + counter + "' style = 'width: 100px; height: 100px; background-color: blue; border: none; position: fixed;' onmousedown = 'drag(true)' onmouseup = 'drag(false)' onClick = 'drag(false)'>Move this Button</button>";
}

` 注意:这不包括HTML,因为Stackoverflow不能正确显示,所以只有JS,请访问JSFiddle以查看完整(创建多个按钮并拖动最后一个!):https://jsfiddle.net/2nyc4a83/

1 个答案:

答案 0 :(得分:0)

我在你的函数 drag()中添加了一个新参数。在事件 onmousedown onmouseup onClick 上,当前对象的 id 将用作<的参数强>拖动()即可。代码如下所示的示例:<button ... onmousedown = 'drag(true, this.id)'>Move this button</button>

id 将保存在全局变量中,以便您稍后可以在onmousemove函数中访问它,如下所示:

obj = document.getElementById(obj_id);

-> jsfiddle

相关问题