Моя кнопка может перемещаться, но странно, я не могу понять, что-то не так со смещением.Перемещение кнопок на странице с помощью JavaScript
Я хочу, чтобы мои кнопки перемещались курсором мыши, но теперь он движется не так, как я хочу, а иногда и исчезает.
Кроме того, новые созданные кнопки перекрывают друг друга, я не знаю, как это решить, и лучше выглядите.
var coorA;
var coorB;
var btn = null;
function mousedown() {
if (event.target.tagName === "BUTTON") {
btn = event.target;
coorA = btn.offsetTop;
coorB = btn.offsetLeft;
}
}
function mouseup() {
btn = null;
}
function mousemove() {
if (btn !== null) {
btn.style.top = (event.clientY - coorA) + "px";
btn.style.left = (event.clientX - coorB) + "px";
}
}
function createButton() {
var button = document.createElement("BUTTON");
var msg = document.getElementById("word").value;
if (msg.length > 0) {
var t = document.createTextNode(msg);
button.appendChild(t);
document.body.appendChild(button);
}
document.getElementById("word").value = "";
}
document.getElementsByTagName("body")[0].addEventListener("mousedown", mousedown);
document.getElementsByTagName("body")[0].addEventListener("mousemove", mousemove);
document.getElementsByTagName("body")[0].addEventListener("mouseup", mouseup);
body {
background-color: black;
}
#word {
padding: 10px 30px;
font-size: 14px;
}
button {
position: absolute;
background-color: #e7e7e7;
color: #000;
font-weight: 700;
padding: 10px 30px;
font-size: 14px;
border: 1px solid gray;
}
#add {
position: relative;
background-color: #e7e7e7;
color: #000;
font-weight: 700;
padding: 10px 30px;
font-size: 14px;
}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Poetry-yuc217</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<form>
<input id = "word" type = "text" name = "word">
<input id = "add" type = "button" value = "Add Word" onclick = "createButton()">
<br>
</form>
<button type="button" >this</button>
</div>
enter code here
</body>
</html>
Большое спасибо! Я все еще немного смущен тем, что на самом деле означает «событие». Из того, что я узнал, событие - это все действия на странице. И это не так понятно ... – RhumB
Добро пожаловать! Я пытался ответить вам, но был ограничен персонажами, поэтому я отредактировал его в главном ответе выше. –