使用 JavaScript 移动 Div 盒子

4

我想创建一个300像素乘以300像素的div盒子,当用户将鼠标放在盒子上时,它会移动几个像素。唯一的问题是当div到达浏览器大小的末端时,我希望它开始向另一个方向移动,并且不会让窗口滚动。非常感谢任何帮助。

<div style="left:300px; top:300px; width:300px; height:300px; background:blue;>
</div>

这是 Oleg 的代码,我在 Firefox 中运行时遇到了问题,是我做错了什么吗?
<html>
<head>
<script>
window.onload = function () {
var speed = 10, // the box will move by 10 pixels on every step
direction = 1, // 1 = move right; -1 = move left
boxElement = document.getElementById('theIdOfTheBox');

if (boxElement) {
    boxElement.addEventListener('mouseover', function () {
        // Calculate and store some of the box coordinates:
        var boxLeftPos = boxElement.offsetLeft,
            boxRightPos = boxLeftPos + boxElement.offsetWidth;
        // When right side of the box goes too far - change direction:
        if (boxRightPos > document.body.offsetWidth) {
            direction = -1;
        }
        // When left side of the box goes too far - change direction:
        if (boxLeftPos < 0) {
            direction = 1;
        }
        // Recalculate position:
        boxElement.style.left = (boxLeftPos + speed * direction) + 'px';
    });
 }
};
</script>

<style>
#theIdOfTheBox {
position: absolute;
left:100px;
top:100px;
width:300px;
height:300px;
background:blue;
}
</style>


</head>

<body>
<div id="theIdOfTheBox">box</div>
</body>



</html>

你能发布你现在的JavaScript吗?或者你还没有任何代码呢? - PurkkaKoodari
5个回答

11

首先创建一对变量,用于跟踪速度和方向:

var speed = 10, // the box will move by 10 pixels on every step
    direction = 1; // 1 moves in the positive direction; -1 vice versa

然后获取对您的框的引用并将事件处理程序附加到其“mouseover”事件:

var boxElement = document.getElementById('theIdOfTheBox');

if (boxElement) {
    boxElement.addEventListener('mouseover', function () {
        // Calculate and store some of the box coordinates:
        var boxLeftPos = boxElement.offsetLeft,
            boxRightPos = boxLeftPos + boxElement.offsetWidth;
        // When right side of the box goes too far - change direction:
        if (boxRightPos > document.body.offsetWidth) {
            direction = -1;
        }
        // When left side of the box goes too far - change direction:
        if (boxLeftPos < 0) {
            direction = 1;
        }
        // Recalculate position:
        boxElement.style.left = (boxLeftPos + speed * direction) + 'px';
    });
}

全部完成,这里是一个让你可以随意玩耍的 jsfiddle

需要注意的是,在CSS中使用了position: absolute;,并且需要等待DOM加载完成才能安全地执行getElementById操作。

如果你想要避免使用偏移量,你可以尝试解析和操作框的边距或填充。

动画

如果你想要动画化你的方框移动,你可以尝试使用CSS动画。只需将以下内容添加到CSS中你的方框样式声明:

-webkit-transition: left 0.3s 0.1s ease-out;
上述代码将在webkit浏览器中动画化任何对left属性的更改。你可以添加其他供应商前缀(也可以不添加,以便与未来版本兼容),以启用在支持该功能的其他浏览器中进行动画处理。
编辑
关于您在浏览器启动时运行脚本的评论:
首先,请确保将JavaScript代码包装在<script></script>标记中,如果您要将其嵌入HTML页面中。您可以运行验证器(例如validator.w3.org)以确保您具有正确的文档结构。
其次,将代码放置在这些标记内,尽可能靠近文档主体的末尾,即</body>
您还可以将整个JavaScript代码包装在一个函数中,该函数将在文档完全加载后执行。这样,代码可以从文档头部(或远程需求)放置,但是为什么要这样做呢?下面是实现方法:
window.addEventListener('load', function () {
    // ... the code goes here
});

一种(不推荐的)替代方案是:

window.onload = function () {
    // ... the code goes here
};
在HTML中,可以这样写(请尽量避免使用此方法,下面仅为举例):

Or

<body onload="someFunction();">

因此,生成的代码可能如下所示:

<!DOCTYPE html>
<html>
<head>
    <style>
        /* ... the CSS goes here */
    </style>
</head>
<body>
    <div id="box">I'm a box.</div>
    <script>
        // ... the JavaScript code goes here
    </script>
</body>
</html>

关于 Internet Explorer 的特别说明

在低于版本9的Internet Explorer中不支持addEventListener。您应改用attachEvent


嘿,我该如何让这个脚本在浏览器启动时加载?我尝试粘贴脚本,但什么也没有发生。 - Gregwest85
@Gregwest85 在你刚刚发布的代码中,JavaScript 是在浏览器创建 <div> 元素之前执行的。请查看我更新的不同技巧以规避这种情况。 - Oleg
@Gregwest85 我完全复制并粘贴了你编辑后的代码,在 Firefox 19 和 Google Chrome 26 上都能正常运行。可能是其他因素在干扰吗?你是在服务器上运行它吗?也许旧版本被缓存了?或者你忘记保存更改了…… - Oleg
我要尝试更新Firefox。非常感谢您的帮助,我真的很感激。我现在只有一个更快的问题,就是这个框从左到右移动。如果我想让它上下移动,我该如何实现? - Gregwest85
@Gregwest85 要垂直移动框,您可以操作 boxElement.style.top 属性,并使用 offsetTopoffsetHeight 计算框的位置。如果页面可滚动,您还可以考虑查看 window.scrollTop 属性。 - Oleg
显示剩余7条评论

1
<script>
 var topPos = 0;
 var leftPos = 0;
 var leftAdder = 1;
 var topAdder = 1;
 var id;

    function move() {  
        clearInterval(id);
        id = setInterval(frame, 3);

        function frame() {

        leftPos = leftPos + leftAdder;
        topPos = topPos + topAdder; 
        document.getElementById("box").style.left = leftPos + 'px'; 
        document.getElementById("box").style.top = topPos + 'px'; 

        if (leftPos == 500) {
            leftAdder = -1;  
        }
        if (topPos == 350) {
            topAdder = -1;  
        }
        if (leftPos == 0) {
            leftAdder = 1;  
        }
        if (topPos == 0) {
            topAdder = 1;  
        }  
        }
    }

    function stop(){
        clearInterval(id);
    }

</script>

0
如果您想输入箭头来指示框的移动,我们可以使用这段代码。尝试一下看看;
        <script>
            var topPos = 0;
            var leftPos = 0;
            var id;

            function moveRight() {  
              clearInterval(id);
              id = setInterval(frame, 10);
              function frame() {
                if (leftPos == 350) {
                  clearInterval(id);
                  gameOver();
                } else {
                  leftPos++; 
                  document.getElementById("box").style.left = leftPos + 'px'; 
                }
              }
            }

            function moveLeft() {  
              clearInterval(id);
              id = setInterval(frame, 10);
              function frame() {
                if (leftPos == 0) {
                  clearInterval(id);
                  gameOver();
                } else {
                  leftPos--; 
                  document.getElementById("box").style.left = leftPos + 'px'; 
                }
              }
            }

            function moveDown() {  
              clearInterval(id);
              id = setInterval(frame, 10);
              function frame() {
                if (topPos == 350) {
                  clearInterval(id);
                  gameOver();
                } else {
                  topPos++; 
                  document.getElementById("box").style.top = topPos + 'px'; 
                }
              }
            }

            function moveUp() {  
              clearInterval(id);
              id = setInterval(frame, 10);
              function frame() {
                if (topPos == 0) {
                  clearInterval(id);
                  gameOver();
                } else {
                  topPos--; 
                  document.getElementById("box").style.top = topPos + 'px'; 
                }
              }
            }

            function gameOver(){
                leftPos = 0;
                topPos = 0;
                alert("Game Over...");
                document.getElementById("box").style.top = '0px'; 
                document.getElementById("box").style.left = '0px'; 
            }
        </script>

0

根据描述,我认为您想要动画化您的 div 的高度。如果您能够使用 Jquery,您可以尝试以下代码:

$('.div').hover(function() {
    $(this).animate({
        height: $(document).height() - 50
    }, 300);
},function() {
    $(this).animate({
        height: '30px'
    }, 300);
});

演示: http://jsfiddle.net/CvhkM/4469/


0
这应该可以工作:

Javascript

var over = false;
var dir = 0;
var speed = 10;

window.onload = function () {
    var div = document.getElementById("myDiv");
    var top = 10;
    div.onmouseover = function () {
        over = true;
        timer;
    }
    div.onmouseout = function () {
        over = false;
        setTimeout(timer, 1);
    }

    var timer = setInterval(function () {
        //direction
        if (div.offsetTop >= document.body.offsetHeight)
            dir = 1;
        else if (div.offsetTop <= 0)
            dir = 0;


        if (over && div.offsetTop < document.body.offsetHeight && dir == 0) {
            top += speed;
        }
        else if (over && top > 0 && dir == 1)
            top -= speed;

        div.style.top = top + "px";
    }, 100);
};

标记语言

<div style="width: 800px; height: 400px">
    <div id="myDiv" style="width: 300px; height: 300px; background: blue; position: absolute">
    </div>
</div>

你的 div 必须被定位为 absolute,第一个 div 代表你的浏览器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接