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

时间:2016-07-06 13:38:26

标签: javascript html css

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

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

2 个答案:

答案 0 :(得分:0)

要水平居中,您可以使用CSS:

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

jsFiddle

答案 1 :(得分:0)

你需要做更多的计算才能做到这一点。

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