代码在jsfiddle中工作,但在html文档中不起作用
我是javascript的初学者,我希望有人可以帮我解决这个问题。 我试图用id做一个div,“移动”,来回滑动。 代码在jsfiddle中工作,但是当我将它放入我的html文档时不起作用。 我尝试将顶部放在一个单独的js文件中,并仅使用代码的最后一行调用头部中的变量:
animateMe($('#move'), 2000);
那没用。 然后我尝试将整个js脚本放入头部,这也无效。 这是我的html文档头部的代码:
$(targetElement).css({ left: '50px', top: '50px' }).animate({ 'left': '200px' },{ duration: speed, complete: function () { $(this).animate({ 'left':'50px' },{ duration: speed, complete: function () { animateMe(this, speed); } }) } } ); }; animateMe($('#move'), 2000);
这是正文中的代码。 我通常使用外部css文档,但为了试图缩短内容,我在这里使用了内联css。
我正在从jsfiddle获取代码并将其放入头部或我的单独的js文件中。 不确定这样做是否会导致脚本无法正常工作。 任何帮助表示赞赏。 谢谢大家。
这是我在jsfiddle工作的链接: http : //jsfiddle.net/wrdweaver6/r8Kf9/
你想把你的代码放在里面
$(document).ready(function() { // Your code here });
要么
window.onload = function() { // Your code here };
在javascript执行之前,需要首先加载所有元素。 使用jsFiddle你不必这样做,但这可能是因为它不能在jsFiddle之外工作。
您需要在代码$(document).ready(function(){
});
周围添加它});
所以你的代码在页面加载后运行。
否则代码将寻找尚不存在的html。
$(document).ready(function(){ $(targetElement).css({ left: '50px', top: '50px' }).animate({ 'left': '200px' },{ duration: speed, complete: function () { $(this).animate({ 'left':'50px' },{ duration: speed, complete: function () { animateMe(this, speed); } }) } } ); }; animateMe($('#move'), 2000); });