【发布时间】:2017-07-09 17:12:47
【问题描述】:
所以我正在(和一个朋友)编写一个 Drag 'n Drop 系统,其中包含用于纯 JS 中 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/
【问题讨论】:
-
我刚刚解决了你的问题.. 将在几分钟内上传一个 jsfiddle
标签: javascript html drag-and-drop targeting