使用javascript移动Div Box [英] Moving Div Box using javascript

查看:101
本文介绍了使用javascript移动Div Box的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试创建一个300像素的300像素div框,当用户将鼠标放在框上时,它会移动几个像素。唯一的事情是,当div到达浏览器大小的末尾时,我希望它以另一种方式开始移动,而不是使窗口滚动。任何帮助将不胜感激。

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

这是oleg的代码,在firefox中,我做错了什么?

 < html> 
< head>
< ;脚本>
window.onload = function(){
var speed = 10,//这个盒子在每一步移动10个像素
direction = 1,// 1 =向右移动; -1 =向左移动
boxElement = document.getElementById('theIdOfTheBox');

if(boxElement){
boxElement.addEventListener('mouseover',function(){
//计算并存储一些盒子坐标:
var boxLeftPos = boxElement.offsetLeft,
boxRightPos = boxLeftPos + boxElement.offsetWidth;
//当盒子的右侧如果(boxRightPos> document.body.offsetWidth){
方向= -1;
}
//当方框的左侧变得太远 - 改变方向:
if(boxLeftPos< 0){
direction = 1;
}
//重新计算位置:
boxElement.style.left =(boxLeftPos + speed * direction)+'px';
});
}
};
< / script>

< style>
#theIdOfTheBox {
position:absolute;
left:100px;
top:100px;
width:300px;
height:300px;
背景:蓝色;
}
< / style>


< / head>

< body>
< div id =theIdOfTheBox>方块< / div>
< / body>



< / html>


解决方案

首先创建一个跟踪速度和方向:

  var speed = 10,//每个步骤方框移动10个像素
方向= 1; // 1向正方向移动; -1反之亦然

然后抓住您的盒子的引用并将事件处理程序附加到其鼠标悬停事件:

  var boxElement = document.getElementById('theIdOfTheBox'); 
$ b $ if(boxElement){
boxElement.addEventListener('mouseover',function(){
//计算并存储一些框坐标:
var boxLeftPos = boxElement.offsetLeft,
boxRightPos = boxLeftPos + boxElement.offsetWidth;
//当盒子右边过分 - 改变方向:
if(boxRightPos> document.body.offsetWidth ){
direction = -1;
}
//当方框左侧变得太远时 - 改变方向:
if(boxLeftPos< 0){
方向= 1;
}
//重新计算位置:
boxElement.style.left =(boxLeftPos + speed * direction)+'px';
});
}

全部完成,这里是 jsfiddle 让你玩得开心。



但是,请注意 position:absolute; 在CSS中,并且您需要等待DOM加载才能安全地执行 getElementById 操作。

如果您想避免使用偏移量,您可能需要解析并操作边框或边框的填充。



动画

如果您想为动画框的动画制作动画,可以尝试CSS动画。只需将以下内容添加到CSS中的样式声明中:

  -webkit-transition:left 0.3s 0.1s ease退房手续; 

上面的代码会动画 left webkit浏览器中的属性。您可以添加其他供应商前缀(并且与以后的版本不兼容),以便在支持它的其他浏览器中启用动画。



编辑



关于您在浏览器启动时运行脚本的评论: 首先,确保将JavaScript代码包装在< ;脚本>< / script> 标记,如果您将它嵌入到HTML页面中。您可以运行验证程序(例如 validator.w3.org ),以确保您拥有正确的文档结构。



其次,将代码放置在尽可能接近文档正文结尾的代码中,即< / body>

您也可以将整个JavaScript代码封装在一个函数中,该函数将在文档完全加载后执行。通过这种方式,代码可以从文档头放置(或远程需要)(但为什么要这么做?)。以下是它的完成方式:

  window.addEventListener('load',function(){
// ...代码在这里
});

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

  window.onload = function(){
// ...代码在这里
};

或者(请避免这个,这只是一个例子)HTML:

 < body onload =someFunction();> 

因此,生成的代码可能看起来像:

 <!DOCTYPE html> 
< html>
< head>
< style>
/ * ... CSS在这里* /
< / style>
< / head>
< body>
< div id =box>我是一个盒子。< / div>
< script>
// ... JavaScript代码在这里
< / script>
< / body>
< / html>

有关Internet Explorer的特别说明



在版本9以下的Internet Explorer中不支持 addEventListener 。您应该使用 attachEvent

I am trying to create a 300px by 300 px div box that moves a few pixels when the user has their mouse on the box. The only thing is when the div hits the end of the browser size I want it to to start moving the other way and not make the window scroll. Any help would be greatly appreciated.

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

This is oleg's code that I am having trouble running in firefox, am i doing something wrong?

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

解决方案

Start by creating a couple of variable that keep track of speed and direction:

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

Then grab a reference to your box and attach an event handler to its "mouseover" event:

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';
    });
}

All done, here's a jsfiddle for you to play around with.

Mind, however, the position: absolute; in the CSS and the fact that you need to wait for the DOM to load to be able to safely perform the getElementById operation.

If you want to avoid usage of offsets, you may want to parse and manipulate margins or padding of the box instead.

Animation

If you want to animate the movement of your box, you can try CSS animations. Just add the following to the style declaration of your box in the CSS:

-webkit-transition: left 0.3s 0.1s ease-out;

The above code will animate any changes in left property in webkit browsers. You can add other vendor prefixes (and none for compatibility with future releases) to enable animation in other browsers that support it.

EDIT

Regarding your comment with running the script on browser launch:

First of all make sure to wrap the JavaScript code in <script></script> tags if you are embedding it in an HTML page. You can run a validator (e.g. validator.w3.org) to ensure you have a correct document structure.

Secondly, place the code inside those tags as close as possible to the end of the body of your document, i.e. </body>.

You can also wrap the entire JavaScript code in a function that will be executed once the document is fully loaded. This way the code can be placed (or remotely required) from the document head (but why would you want that?). Here's how it's done:

window.addEventListener('load', function () {
    // ... the code goes here
});

A (non-recommended) alternative is:

window.onload = function () {
    // ... the code goes here
};

Or (please avoid this, it's just an example) in HTML:

<body onload="someFunction();">

So, the resulting code might look like:

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

Special note regarding Internet Explorer

There's no support for addEventListener in Internet Explorer below version 9. You should use attachEvent instead.

这篇关于使用javascript移动Div Box的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆