所以我有这样的代码:
<!DOCTYPE html>
<html>
<script>
score = 0
function hi(buttonID){
score += 1
document.getElementById("label123").innerHTML = score
}
</script>
<button onclick="hi(this)" id="Button123">
<img src="button.png" alt="Button" width="100px" height="100px" draggable="true">
</button>
<label id="label123">Click it!</label>
<h1> clicker.io </h1>
</html>
我想让按钮(Button123)可拖动。这将使用户能够体验到在屏幕上任意移动按钮的能力。
我的旧的,滞后的解决方案(在firefox上每秒4帧)
var btn = document.getElementById("btn");
function drag(e) {
btn.style.left = `${e.pageX - 10}px`;
btn.style.top = `${e.pageY - 10}px`;
}
btn.addEventListener("mousedown", () =>
document.addEventListener("mousemove", drag)
);
btn.addEventListener("mouseup", () =>
document.removeEventListener("mousemove", drag)
);
#btn {
position: absolute;
}
<button id="btn">Button</button>
使用transform: translate()
的新解决方案(firefox上最小40 FPS)
var btn = document.getElementById("btn");
function drag(e) {
btn.style.transform = `translate(${e.pageX - 20}px, ${e.pageY - 20}px)`;
}
btn.addEventListener("mousedown", () =>
document.addEventListener("mousemove", drag)
);
btn.addEventListener("mouseup", () =>
document.removeEventListener("mousemove", drag)
);
<button id="btn">Button</button>