小提琴:http: //jsfiddle.net/uQAmQ/2/
您不应该在绝对定位的元素上“平移”,因为窗口的宽度和高度会根据图像不断变化。更平滑的解决方案涉及使用背景图像。有关使用的逻辑,请参阅我的答案的中间部分。
考虑这个 JavaScript(阅读评论;HTML + CSS at fiddle):
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var avatar = document.getElementById("avatar");
var avatarWidth = avatar.width;
var avatarHeight = avatar.height;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
/* Logic: Move */
var ratioY = (avatarHeight - windowHeight) / windowHeight;
var ratioX = (avatarWidth - windowWidth) / windowWidth;
function updateImgPosition( e ) {
var mouseY = e.pageX; //e.pageX, NOT e.x
var mouseX = e.pageY;
var imgTop = ratioY*(-mouseY);
var imgLeft = ratioX*(-mouseX);
document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";
}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();
其背后的逻辑:
- 不能使用相对单位,因为图像大小是用绝对单位指定的。
- 偏移量应根据特定比率变化,类似于:
image size
除以 window size
。
但是,这个比例并不完整:图像会在窗口的左下角消失。要解决此问题,请从图像大小中减去窗口大小。结果可以在变量ratioX
和的代码中找到ratioY
。
之前的代码必须在window.onload
事件中加载,因为图像的大小是动态计算的。因此,正文中还包含一个 HTML 元素。
通过在代码中指定背景的大小,可以将相同的代码编写得更小更高效。请参阅此改进的代码。小提琴:http: //jsfiddle.net/uQAmQ/3/
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var avatarWidth = 1690;
var avatarHeight = 1069;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
/* Logic: Move */
var ratioY = (avatarHeight - windowHeight) / windowHeight;
var ratioX = (avatarWidth - windowWidth) / windowWidth;
function updateImgPosition( e ) {
var mouseX = e.pageX; //e.pageX, NOT e.x
var mouseY = e.pageY;
var imgTop = ratioY*(-mouseY);
var imgLeft = ratioX*(-mouseX);
document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";
}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();
如果您不介意代码可读性降低,以下代码是最好的解决方案,
Fiddle: http: //jsfiddle.net/uQAmQ/4/:
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var ratioY = (windowHeight - 1069) / windowHeight;
var ratioX = (windowWidth - 1690) / windowWidth;
window.onmousemove = function( e ) {
document.body.style.backgroundPosition = ratioX * e.pageX + "px " + ratioY * e.pageY + "px";
}
})();