I use "copy" function to generate new objects(e1,e2,e3......),the following is my code.
<script src="js檔/設備/drag.js"></script>
.
.
.
<script>
var id_num=0;
var wid=0;
function copy(){
var d1=document.getElementById("back_for_equi");
var input=document.createElement("input");
id_num=id_num+1;
input.type="image";
input.src="種子社群街區/設備切片/實際大小/設備1(106.86X266.42px).png";
input.id="e"+id_num;
input.className="drag";
//why can't "drag" function run?
input.style.position="absolute";
input.style.height="100px";
input.style.left=50+wid+"px";
wid=50+wid;
input.zIndex="3";
input.style.touchAction="none";
document.body.appendChild(input);
//new object will show like
//<input type="image" src="種子社群街區/設備切片/實際大小/設備
//1(106.86X266.42px).png" id="e2" class="drag" style="position:
//absolute; height: 100px; left: 100px; touch-action: none;">
}
</script>
and I reference it on a button named "equi1"
In fact, I need to achieve the effect of dragging an object, and this object generated by clicking a button. That is, if you click a button it will generate a new object(e1,e2...), and this new object can be dragged in a block. I use "e2" as a trial. The following is a function of the "drag" thing. And how do I reference "correctly" it on "e2"(on a new object)?
$(function(){
var dragItem = document.querySelector("#e2");
var container = document.querySelector("body");
var active = false;
var currentX;
var currentY;
var initialX;
var initialY;
var xOffset = 0;
var yOffset = 0;
/*偵聽器處理觸控事件*/
container.addEventListener("touchstart", dragStart, false);
container.addEventListener("touchend", dragEnd, false);
container.addEventListener("touchmove", drag, false);
/*偵聽器處理滑鼠事件*/
container.addEventListener("mousedown", dragStart, false);
container.addEventListener("mouseup", dragEnd, false);
container.addEventListener("mousemove", drag, false);
function dragStart(e) {
if (e.type === "touchstart") {
initialX = e.touches[0].clientX - xOffset;
initialY = e.touches[0].clientY - yOffset;
} else {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
}
if (e.target === dragItem) {
active = true;
}
}
function dragEnd(e) {
initialX = currentX;
initialY = currentY;
active = false;
}
function drag(e) {
if (active) {
e.preventDefault();
if (e.type === "touchmove") {
currentX = e.touches[0].clientX - initialX;
currentY = e.touches[0].clientY - initialY;
} else {
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
}
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, dragItem);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
dragStart("#e2")
})
I think drag.js is correct because if I reference it on another object, it functioned. But if I use it on a new object "e2", it doesn't work, but "Console" shows nothing error. Because drag works on another object, such as "equi1", but the only doesn't work on new objects, so maybe this problem is by "order" problem?