那里!我有一个获取问题#drag
元素移动平稳。
我看这篇文章:http://www.html5rocks.com/en/tutorials/speed/animations/#debouncing-mouse-events http://www.html5rocks.com/en/tutorials/speed/animations/#debouncing-mouse-events
它说:“问题是mousemove
移动元素时发生的事件mousemove 事件触发过多
所以,我尝试使用他们的方法:使用requestAnimationFrame
+ boolean checking
.
看看这个小提琴的现场表演:https://jsfiddle.net/5f181w9t/ https://jsfiddle.net/5f181w9t/
HTML :
<div id="drag">this is draggable</div>
CSS :
#drag {width:100px; height:50px; background-color:red; transform:translate3d(0, 0, 0); }
JS :
var el = document.getElementById("drag"),
startPosition = 0, // start position mousedown event
currentPosition = 0, // count current translateX value
distancePosition = 0, // count distance between "down" & "move" event
isMouseDown = false; // check if mouse is down or not
function mouseDown(e) {
e.preventDefault(); // reset default behavior
isMouseDown = true;
startPosition = e.pageX; // get position X
currentPosition = getTranslateX(); // get current translateX value
requestAnimationFrame(update); // request 60fps animation
}
function mouseMove(e) {
e.preventDefault();
distancePosition = (e.pageX - startPosition) + currentPosition; // count it!
}
function mouseUp(e) {
e.preventDefault();
isMouseDown = false; // reset mouse is down boolean
}
function getTranslateX() {
var translateX = parseInt(getComputedStyle(el, null).getPropertyValue("transform").split(",")[4]);
return translateX; // get translateX value
}
function update() {
if (isMouseDown) { // check if mouse is down
requestAnimationFrame(update); // request 60 fps animation
}
el.style.transform = "translate3d(" + distancePosition + "px, 0, 0)";
// move it!
}
el.addEventListener("mousedown", mouseDown);
document.addEventListener("mousemove", mouseMove);
document.addEventListener("mouseup", mouseUp);
这是实现它的正确方法吗?
我的代码有什么问题吗?
thanks