我有一个脚本,可以在用户移动鼠标时将图像稍微向左或向右移动。问题是当我需要它始终位于中心时,此图像始终位于窗口的左上角。
<html>
<head>
</head>
<body>
<img id="logo" src="logoHeader.png" style="position:absolute;" />
</body>
<script lang="javascript">
function updateLogoPosition( e )
{
var logo = document.getElementById("logo");
var m = e.x / 12;
logo.style.left = m + "px";
}
document.onmousemove = updateLogoPosition;
</script>
</html>
最佳答案
你必须做更多的计算才能做到这一点。
您需要知道视口(viewport)的宽度和高度才能找到中间点。然后你需要标准化鼠标位置,这样你就可以计算出中心线的偏移量,而不是像你 e.x 那样计算从左上角的偏移量。
应该这样做,其中“修改器”将允许您更改偏移的暴力程度。
<html>
<head>
</head>
<body>
<img id="logo" src="http://placehold.it/150x150" style="position:absolute;" />
<script>
window.onload = setInitialLogoPosition;
document.onmousemove = updateLogoPosition;
function setInitialLogoPosition(){
var bodyHeight = document.body.clientHeight;
var bodyWidth = document.body.clientWidth;
var logo = document.getElementById("logo");
var logoWidth = logo.width;
var logoHeight = logo.height;
var leftOffset = (bodyWidth/2 - logoWidth/2);
var topOffset = (bodyHeight/2 - logoHeight/2);
logo.style.left = leftOffset;
logo.style.top = topOffset;
}
function updateLogoPosition( e ){
// Get height and width of body
var bodyHeight = document.body.clientHeight;
var bodyWidth = document.body.clientWidth;
// Get height and width of logo
var logo = document.getElementById("logo");
var logoWidth = logo.width;
var logoHeight = logo.height;
/* Normalise the mouse so that 0 is the centre
with negative values to the left and positive to the right */
var x = (e.x / bodyWidth * 100) - 50;
var y = (e.y / bodyHeight * 100) - 50;
// Calculate the position of the logo without mouse manipulation
var leftOffset = (bodyWidth/2 - logoWidth/2);
var topOffset = (bodyHeight/2 - logoHeight/2);
// Set violence of offset
var modifier = 0.5;
// Add the mouse offset to the central position
leftOffset += (x * modifier);
topOffset += (y * modifier);
// Apply the calculated position to the logo
logo.style.left = leftOffset + "px";
logo.style.top = topOffset + "px";
}
</script>
</body>
</html>
关于javascript - 用鼠标位置更新 x 后保持图像居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38225446/