[英]move div using javascript
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><
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;
您的主要问题是,在设置好左右两个值之后,您不再更改任何内容,它在left: 10px; right: 10px;
是静态的left: 10px; right: 10px;
left: 10px; right: 10px;
you have to keep changing one of those values instead. 您必须继续更改这些值之一。
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';
for both right and left. 左右两边
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.