我目前正在尝试在javaScript中在屏幕上移动鼠标时创建图像的视差移动。为此,我设法创建了以下代码:
var mainImage = document.getElementById("mainLogo");
var currentX = '';
var currentY = '';
var movementConst = .5;
function moveMainImage(event)
{
if (currentX = '') currentX = event.screenX;
var diffX = event.screenX - currentX;
currentX = event.screenX;
if (currentY = '') currentY = event.screenY;
var diffY = event.screenY - currentY;
currentY = event.screenY;
var movementX = diffX * movementConst;
var movementY = diffY * movementConst;
var newX = mainImage.style.left + movementX;
var newY = mainImage.style.top + movementY;
mainImage.style.left = newX + "px";
mainImage.style.top = newY + "px";
}
document.addEventListener("mousemove", moveMainImage);
我遇到的问题是“ mousemove”事件侦听器仅发生一次,而每次鼠标移动时都不会调用。我对javaScript还是很陌生,所以如果这是一个简单的问题,我深表歉意。请帮忙吗?