var move = function() {
var figur_1 = document.getElementById('figur_1');
figur_1.style.top++;
window.requestAnimationFrame(move);
}
move();
我想在屏幕上移动ID为 figur_1 的div。
如何做到这一点?
var move = function() {
var figur_1 = document.getElementById('figur_1');
figur_1.style.position = 'absolute';
figur_1.style.top += '1px';
window.requestAnimationFrame(move);
}
move();
也没有动画。它只是将DIV 1px向下移动!
答案 0 :(得分:0)
我发现一个简单易用的模式可以移动一个包含少量代码的元素。
var move = function() {
var figur_1 = document.getElementById('figur_1');
figur_1.style.position = "absolute";
figur_1.style.top = "100px";
}
move();
var move = function() {
var figur_1 = document.getElementById('figur_1');
figur_1.style.position = "absolute";
figur_1.style.top = "100px";
}
move();
<div id="figur_1">TEST</div>
吨
您也可以使用.style.bottom/top/left/right
答案 1 :(得分:0)
您无法通过单一功能实现此功能。您需要使用至少两个功能。一个是mousedown
事件,另一个是mouseup
事件。因为,在用户释放鼠标键后,您不再需要拖动操作。
HTML:
<div id="figur_1">
This div is movable. Lets try dragging.
</div>
CSS:
#figur_1{
position: absolute;
height: 100px;
width: 100px;
background: #0000ff;
left: 0px;
top: 0px;
color: yellow;
cursor: move;
}
JS:
figur_1.onmousedown = function (e) {
var figur_1 = document.getElementById("figur_1");
var left = parseInt( window.getComputedStyle(figur_1).getPropertyValue("left") );
var top = parseInt( window.getComputedStyle(figur_1).getPropertyValue("top") );
var mouseX = e.clientX;
var mouseY = e.clientY;
document.onmousemove = function (e) {
var dx = mouseX - e.clientX;
var dy = mouseY - e.clientY;
figur_1.style.left = left - dx + "px";
figur_1.style.top = top - dy + "px";
};
};
figur_1.onmouseup = function () {
document.onmousemove = null;
};
这是一个有效的jsfiddle:https://jsfiddle.net/sajibche/4xfuemrb/
答案 2 :(得分:0)