此代码中的setInterval无法正常工作

<script language="javascript">
    x = y = 0;
    function mvtb(p, g){
        i = 0;
        tmp = setInterval(function (){
            if(i < 100 && i >= 0){
                document.getElementById("plan").scrollTop = 200*(y+((y-g)*(i/100)));
                document.getElementById("plan").scrollLeft = 660*(x+((x-p)*(i/100)));
                i++;
            }
            else if(i == 100){
                clearInterval(tmp);
            }
        }, 10);
        x = p; y = g;
    }
</script>


的CSS

<style>
#plan {overflow: hidden; height: 200px; width: 660px; background: #444;}
.plan {width: 1980px;}
.plan table {height: 200px; width: 660px;}
</style>


的HTML

<body style="background: black; color: white;">
<center>
<div id="plan">
<table class="plan">
    <tr id="g0">
        <td class="p0"><table bgcolor="gray"><tr><td>0 0</td></tr></table></td>
        <td class="p1"><table bgcolor="blue"><tr><td>1 0</td></tr></table></td>
        <td class="p2"><table bgcolor="yellow"><tr><td>2 0</td></tr></table></td>
    </tr>
    <tr id="g1">
        <td class="p0"><table bgcolor="green"><tr><td>0 1</td></tr></table></td>
        <td class="p1"><table bgcolor="orange"><tr><td>1 1</td></tr></table></td>
        <td class="p2"><table bgcolor="red"><tr><td>2 1</td></tr></table></td>
    </tr>
    <tr id="g2">
        <td class="p0"><table bgcolor="brown"><tr><td>0 2</td></tr></table></td>
        <td class="p1"><table bgcolor="white"><tr><td style="color: black">1 2</td></tr></table></td>
        <td class="p2"><table bgcolor="crimson"><tr><td>2 2</td></tr></table></td>
     </tr>
</table>
</div>
<br /><br /><br />Move Table<br />
<button onClick="mvtb(0, 0);">0 0</button> &nbsp; <button onClick="mvtb(1, 0);">1 0</button> &nbsp; <button onClick="mvtb(2, 0);">2 0</button><br />
<button onClick="mvtb(0, 1);">0 1</button> &nbsp; <button onClick="mvtb(1, 1);">1 1</button> &nbsp; <button onClick="mvtb(2, 1);">2 1</button><br />
<button onClick="mvtb(0, 2);">0 2</button> &nbsp; <button onClick="mvtb(1, 2);">1 2</button> &nbsp; <button onClick="mvtb(2, 2);">2 2</button><br />
</center>
</body>

最佳答案

试试这个吧。仅在动画完成后更新g和p,并在计算新的scrollTop / scrollLeft时交换减法。您还需要确保循环运行100次,而不是99次。JSFiddle

x = y = 0;

function mvtb(p, g) {
    var i = 1;
    var tmp = setInterval(function() {
        if (i <= 100 ) {
            document.getElementById("plan").scrollTop = 200 * (y + ((g - y) * (i / 100)));
            document.getElementById("plan").scrollLeft = 660 * (x + ((p - x) * (i / 100)));
            i++;
        }
        else {
            clearInterval(tmp);
            x = p;
            y = g;
        }
    }, 10);
}

10-07 12:53