Html 使用javascript移动Div Box
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15792855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moving Div Box using javascript
提问by Gregwest85
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.
我正在尝试创建一个 300 像素 x 300 像素的 div 框,当用户将鼠标放在框上时,它会移动几个像素。唯一的事情是当 div 到达浏览器大小的末尾时,我希望它开始以另一种方式移动而不是使窗口滚动。任何帮助将不胜感激。
<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?
这是我在 Firefox 中运行时遇到问题的 oleg 代码,我做错了什么吗?
<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>
回答by Oleg
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 jsfiddlefor you to play around with.
一切都完成了,这里有一个jsfiddle供你玩。
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.
但是请注意,position: absolute;
在 CSS 中以及您需要等待 DOM 加载才能安全地执行getElementById
操作的事实。
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:
如果要为盒子的运动设置动画,可以尝试使用 CSS 动画。只需将以下内容添加到 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.
上面的代码将left
在 webkit 浏览器中对属性的任何更改进行动画处理。您可以添加其他供应商前缀(为了与未来版本兼容,不添加任何前缀)以在支持它的其他浏览器中启用动画。
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.
首先,<script></script>
如果您将 JavaScript 代码嵌入到 HTML 页面中,请确保将 JavaScript 代码包装在标签中。您可以运行验证器(例如validator.w3.org)以确保您拥有正确的文档结构。
Secondly, place the code inside those tags as close as possible to the end of the body of your document, i.e. </body>
.
其次,将这些标签内的代码尽可能靠近文档正文的末尾,即</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:
您还可以将整个 JavaScript 代码包装在一个函数中,该函数将在文档完全加载后执行。通过这种方式,可以从文档头放置(或远程需要)代码(但为什么要那样做?)。这是它的完成方式:
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:
或者(请避免这种情况,这只是一个示例)在 HTML 中:
<body onload="someFunction();">
So, the resulting code mightlook 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
关于 Internet Explorer 的特别说明
There's no support for addEventListener
in Internet Explorer below version 9. You should use attachEvent
instead.
addEventListener
版本 9 以下的 Internet Explorer不支持。您应该attachEvent
改用。
回答by indranatha madugalle
<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>
回答by indranatha madugalle
If you're looking to input arrows to dictate the movement of the box, we can use this code. Try and see;
如果您希望输入箭头来指示框的移动,我们可以使用此代码。试试看;
<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>
回答by Prakash Chennupati
Based on the description I think you want to animate the height of your div, If you are able to use Jquery you can try something like this:
根据描述,我认为您想为 div 的高度设置动画,如果您能够使用 Jquery,您可以尝试以下操作:
$('.div').hover(function() {
$(this).animate({
height: $(document).height() - 50
}, 300);
},function() {
$(this).animate({
height: '30px'
}, 300);
});
回答by Hanlet Esca?o
This should work:
这应该有效:
Javascript:
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);
};
Markup:
标记:
<div style="width: 800px; height: 400px">
<div id="myDiv" style="width: 300px; height: 300px; background: blue; position: absolute">
</div>
</div>
Your div has to be positioned absolute, the first div would represent your browser.
您的 div 必须定位为absolute,第一个 div 将代表您的浏览器。