Javascript函数不起作用,代码简单

时间:2013-04-11 02:38:27

标签: javascript

下面的相当简单的代码不起作用。不知道为什么,JS功能可以顺畅地移动图像。 帮助将是伟大的家伙,几乎尝试了一切。

代码已准备好将粘贴复制到php脚本并进行测试。 非常感谢提前

<?php
echo "

<script type='text/javascript'>

var img = document.getElementById( 'test' );

function translate( elem, x, y ) {
    var left = 120,
        top = 120,
        dx = left - x,
        dy = top - y,
        i = 1,
        count = 20,
        delay = 20;

    function loop() {
        if ( i >= count ) { return; }
        i += 1;
        elem.style.left = ( left - ( dx * i / count ) ).toFixed( 0 ) + 'px';
        elem.style.top = ( top - ( dy * i / count ) ).toFixed( 0 ) + 'px';
        setTimeout( loop, delay );
    }

    loop();
}

</script>
";
echo '
</head>
<body>
  <img id="test" src="http://placekitten.com/100/100" style="position:absolute; left:120px; top:120px;">


<a href="#" onclick="translate(\'test\', 30 , 30)">Translate to (0, 200)</a>

</body>
';
?>

1 个答案:

答案 0 :(得分:1)

<!doctype html>
<html>
<head>
<script type='text/javascript'>

function byId(e){return document.getElementById(e);}

function translate( elem, x, y ) {
    var left = 120,
        top = 120,
        dx = left - x,
        dy = top - y,
        i = 1,
        count = 20,
        delay = 20;

    function loop() 
    {
        if ( i >= count ) 
            return;
        i += 1;
        elem.style.left = ( left - ( dx * i / count ) ).toFixed( 0 ) + 'px';
        elem.style.top = ( top - ( dy * i / count ) ).toFixed( 0 ) + 'px';
        setTimeout( loop, delay );
    }
    loop();
}

window.addEventListener('load', myInit, false);

function myInit()
{
    byId('myAnchor').addEventListener('click', handleLinkClick, false);
}

function handleLinkClick(evt)
{
    //translate(byId('test'), 30, 30);  // only works on the #test target.
    translate(this, 30, 30);  // makes the handler work for any element it's attached to.
}
</script>
</head>
<body>
  <img id="test" src="http://placekitten.com/100/100" style="position:absolute; left:120px; top:120px;">
  <a id='myAnchor' href="#">Translate to (0, 200)</a>
</body>
</html>