2013-04-11 61 views
0

下面的很简单的代码是行不通的。不知道为什么,JS功能平稳移动图像。 帮助会很棒,尝试几乎所有的东西。Javascript功能不起作用,简单的代码

准备好将代码粘贴到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> 
'; 
?> 
+0

写了许多感谢你为什么要使用echo打印出来的HTML/JS的JavaScript代码从PHP – Amit 2013-04-11 02:40:31

+0

外面?你可以关闭php标签。 – 2013-04-11 02:41:01

+0

已经试过了,在php外写结果与这里的效果相同 – John 2013-04-11 02:41:18

回答

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> 
+0

男人你真了不起:)工作就像魅力。我很好奇你为什么需要添加这两个功能? – John 2013-04-11 10:13:13

+0

有一个问题,您没有使用link移动图像。这对于此代码至关重要。轻松修复? – John 2013-04-11 10:23:44

+0

了解它:)添加到 John 2013-04-11 10:29:26