下面的代码片段计算鼠标光标在屏幕上的速度。它似乎工作正常,但是,我对它是如何工作有一些疑问。
var div = document.body.children[0],
isOverElem, cX, cY, pX, pY, cTime, pTime;
div.addEventListener('mouseover', function(event) {
if (isOverElem) return;
isOverElem = true;
pX = event.pageX;
pY = event.pageY;
pTime = Date.now();
this.addEventListener('mousemove', move);
});
div.addEventListener('mouseout', function(event) {
if ( event.relatedTarget && !this.contains(event.relatedTarget) ) {
isOverElem = false;
this.removeEventListener('mousemove', move);
this.innerHTML = '';
}
});
function move(event) {
var speed;
cX = event.pageX;
cY = event.pageY;
cTime = Date.now();
if (pTime == cTime) return; // mouseover with mousemove
speed = Math.sqrt( Math.pow(pX - cX, 2) + Math.pow(pY - cY, 2) ) / (cTime - pTime);
this.innerHTML = 'Mouse speed: ' + speed;
setTimeout(function() {
pX = cX;
pY = cY;
pTime = cTime;
}, 10);
}

div {
width: 80%;
height: 200px;
padding: 10px;
line-height: 200px;
font-size: 1.5em;
border: 2px solid red;
}

<div></div>
&#13;
我不明白以下几行:
speed = Math.sqrt( Math.pow(pX - cX, 2) + Math.pow(pY - cY, 2) ) / (cTime - pTime);
为什么这只能使用(pX - cX)/(cTime - pTime)
?为什么需要包含Math.sqrt
和Math.pow
的更复杂的等式?我对算法以及脚本是否正确感兴趣。