简体   繁体   English

jQuery动画不起作用

[英]jQuery animate isn't working

I know this is posted on here multiple other times, and I have looked at every single one of those and modified my code countless times, but I can't seem to get my animate function to work. 我知道它多次发布在这里,我已经查看了其中的每一个并修改了我的代码无数次,但是我似乎无法使我的动画函数正常工作。 I'm trying to get an image of a plane to move from left to right across the screen, stopping halfway. 我正在尝试获取飞机的图像,该图像在屏幕上从左向右移动,停止一半。 Here is my current code: 这是我当前的代码:

HTML: HTML:

<div id="plane">
    <img src="plane.png" alt="" id="plane2" height='100px' width='100px'>
</div>

CSS: CSS:

#plane {
    position: relative;
}

javacript/jQuery: javacript / jQuery的:

function animatePlane() {
    var width = $(document).width / 2;
    $("#plane").animate({
        left: '+=' + width
    }, 500);
}

The problem is that the plane does not move at all. 问题在于飞机根本不动。 I've tried moving the div and the image. 我试过移动div和图像。 I've tried assigning it a $("#plane").click. 我尝试为其分配一个$(“#plane”)。click。 And I've tried many more things. 而且我尝试了更多的事情。 This is my first time trying to use jQuery for moving something, so it's possible I'm missing something simple. 这是我第一次尝试使用jQuery移动某些内容,因此有可能缺少一些简单的内容。 And yes, the function is being called. 是的,该函数正在被调用。 Thank you for any help! 感谢您的任何帮助!

This 这个

var width = $(document).width / 2;

returns NaN as the width function is never called, you probably wanted 返回NaN因为从不调用width函数,您可能想要

var width = $(window).width() / 2;

FIDDLE 小提琴

width is function not property in jQuery. width不是jQuery中的属性。

function animatePlane() {
    var width = $(document).width() / 2;
    $("#plane").stop().animate({
        left: '+=' + width
    }, 500);
}

$(document).width() needs to be called as a function, you need to add opening and closing parenthesis () after the method name. $(document).width()需要作为一个函数来调用,您需要在方法名称后添加$(document).width()括号()

Working example: http://codepen.io/anon/pen/LVZWqd 工作示例: 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM