我知道这是多次在这里发布的,我已经查看了每一个并且无数次地修改了我的代码,但我似乎无法使我的动画功能起作用。我试图让一架飞机的图像在屏幕上从左向右移动,中途停止。这是我目前的代码:
HTML:
<div id="plane">
<img src="plane.png" alt="" id="plane2" height='100px' width='100px'>
</div>
CSS:
#plane {
position: relative;
}
javacript / jQuery的:
function animatePlane() {
var width = $(document).width / 2;
$("#plane").animate({
left: '+=' + width
}, 500);
}
问题是飞机根本不动。我试过移动div和图像。我试过给它分配$(“#plane”)。点击。我已经尝试了很多东西。这是我第一次尝试使用jQuery来移动东西,所以我可能会遗漏一些简单的东西。是的,正在调用该函数。谢谢你的帮助!
答案 0 :(得分:2)
此
var width = $(document).width / 2;
返回NaN
,因为永远不会调用width
函数,您可能需要
var width = $(window).width() / 2;
答案 1 :(得分:1)
width
是jQuery中的函数而不是属性。
function animatePlane() {
var width = $(document).width() / 2;
$("#plane").stop().animate({
left: '+=' + width
}, 500);
}
答案 2 :(得分:1)
$(document).width()
作为函数调用,需要在方法名称后面添加左右括号()
。
工作示例:http://codepen.io/anon/pen/LVZWqd
function animatePlane() {
var width = $(document).width() / 2;
$("#plane img").animate({
left: width+"px"
}, 500);
}
#plane img {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="plane">
<img src="http://lorempixel.com/100/100" alt="" id="plane2" height=100" width=100" />
<br />
<button onclick="animatePlane()">Animate the Image</button>
</div>