javascript 使用javascript移动div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19668224/
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
move div using javascript
提问by Rakim
I have a div and I am trying to move it right and left on page load using js to create a shaking movement.
我有一个 div,我正在尝试使用 js 在页面加载时左右移动它以创建摇晃运动。
My code:
我的代码:
<script type="text/javascript">
obj = document.getElementById('hs');
obj.style.position='relative';
function goRight(){
obj.style.right = 10px;
window.setTimeout(goLeft, 100);
}
function goLeft(){
obj.style.left = 10px;
window.setTimeout(goRight, 100);
}
window.onload =goRight;
</script>
But it doesn't work. The id of my div is hs
.
但它不起作用。我的 div 的 id 是hs
.
The html is:
html是:
<div id="hs">
<h1>hs</h1>
<hr>
</div><
回答by dezman
obj = document.getElementById('hs');
obj.style.position='relative';
function shake(interval) {
obj.style.right = '10px';
setTimeout(function(){
obj.style.right = '0px';
}, interval);
}
setInterval(function(){
shake(500);
}, 1000)
Your main issue was that after both the right and left values were set, you weren't changing anything anymore, it was static at left: 10px; right: 10px;
you have to keep changing one of those values instead.
您的主要问题是,在设置了左右值之后,您不再更改任何内容,它是静态的,left: 10px; right: 10px;
您必须继续更改其中一个值。
回答by Smeegs
I don't know if this is the main problem, but you need to make the 10px into a string.
我不知道这是否是主要问题,但是您需要将10px变成字符串。
obj.style.right = '10px';
obj.style.right = '10px';
for both right and left.
左右两边。