我有改变容器div内容的简单功能。
有一个 <table>
容器内<div>
, 有 2 <td>
s,javascript 简单地向左移动 <table>
它有效,但是onclick
我需要按时间间隔执行移动功能。
<div onclick="move(this.children[0])" class="table_wrap">
<div class="table_scroll" style="left: 0px;">
<table cellpadding="0" cellspacing="5" width="1920px">
<tr>
<td style="background-color: red;">
a
</td>
<td style="background-color: blue;">
b
</td>
</tr>
</table>
</div>
</div>
<script language="javascript">
function move(elem) {
var left = 0
function frame() {
left -= 5; // update parameters
elem.style.left = left + 'px' // show frame
if (left == -965) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 1) // draw every 10ms
}
</script>
和 CSS:
<style type="text/css">
.table_wrap{
position:relative;
overflow:hidden;
width: 967px;
height: 250px;
left: -2px;
top: 5px;
}
.table_wrap .table_scroll{
position: absolute;
text-align:center;
white-space:nowrap;
}
</style>
我尝试使用 setInterval
, 但失败了。
http://jsfiddle.net/hqztm2dt/1/这是 JSfiddle,只需单击红线.. 在此先感谢您的关注!
最佳答案
If you need to move it on interval, see this: http://jsfiddle.net/gsddsxgy/2/ (here the time interval is 3ms)
html:
<div class="table_wrap">
<div id='move' class="table_scroll" style="left: 0px;">
<table cellpadding="0" cellspacing="5" width="1920px">
<tr>
<td style="background-color: red;">
a
</td>
<td style="background-color: blue;">
b
</td>
</tr>
</table>
</div>
</div>
JS:
setInterval(function(){
var elem=document.getElementById('move');
var left = 0
function frame() {
left -= 5; // update parameters
elem.style.left = left + 'px' // show frame
if (left == -965) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 1) // draw every 10ms
}, 3000);
If you need to move the div on click but after a little time gap, see this http://jsfiddle.net/gsddsxgy/
代码:
function move(elem) {
setTimeout(function(){
var left = 0
function frame() {
left -= 5; // update parameters
elem.style.left = left + 'px' // show frame
if (left == -965) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 1) // draw every 10ms
}, 1000);
}
关于javascript以时间间隔执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28560912/