使用鼠标位置更新 x 后保持图像居中

Keep image centered after updating x with mouse position

本文关键字:图像 鼠标 位置 更新      更新时间:2023-09-26

我有一个脚本,当用户移动鼠标时,它会稍微向左或向右移动图像。问题是当我需要它始终保持在中心时,此图像始终位于窗口的左上角。

<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>

您必须进行更多的计算才能执行此操作。

您需要知道视口的宽度和高度才能找到中间。然后,您需要规范化鼠标位置,以便计算与中心线的偏移量,而不是像 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>

要水平居中,您可以使用CSS执行此操作:

<img id="logo" src="logoHeader.png" style="position:relative; text-algin:center; display: block; margin: 0 auto;" />

js小提琴