最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Animate and image up and down in jQuery - Stack Overflow

programmeradmin2浏览0评论

I'm trying to animate and image up and then down with jQuery.

It should behave like this:

When the page loads it shows 50% of the image. If someone clicks on the image it then animates the div up the page. If the user click again it moves back down the page.

html

 <div id="slidebottom" class="slide">
     <div class="inner"><img src="images/sze.jpg" alt="" class="try" /></div>
 </div>

jQuery

$(document).ready(function() {
    $('.try').click(function() {
        $(".inner").animate({
            top: '-=100px'
        }, 2000);
    });
});

How can I reverse the animation after click two? At the moment every time I click, the container moves up.

I'm trying to animate and image up and then down with jQuery.

It should behave like this:

When the page loads it shows 50% of the image. If someone clicks on the image it then animates the div up the page. If the user click again it moves back down the page.

html

 <div id="slidebottom" class="slide">
     <div class="inner"><img src="images/sze.jpg" alt="" class="try" /></div>
 </div>

jQuery

$(document).ready(function() {
    $('.try').click(function() {
        $(".inner").animate({
            top: '-=100px'
        }, 2000);
    });
});

How can I reverse the animation after click two? At the moment every time I click, the container moves up.

Share Improve this question edited Jul 29, 2020 at 23:17 halfer 20.5k19 gold badges108 silver badges201 bronze badges asked Jul 18, 2012 at 8:23 holianholian 7554 gold badges13 silver badges27 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

You can try using the .toggle() method, which takes two functions and alternates between executing each one of them on click:

$(document).ready(function(){
  $('.try').toggle(function() {
    $(".inner").animate({top: '-=100px'}, 2000);
  }, function() {
    $(".inner").animate({top: '+=100px'}, 2000);
  });
});

However, I personally would use a class and CSS3 Transitions.

Try this example. Also note that in order to use the top css property you should either position: relatve; or position: absolute the .inner div.

 var clicked = false
 $('.try').click(function () {
     if (clicked == true) {
         $(".inner").animate({
             top: '0px'
         }, 2000);
         clicked = false;
     } else {
         $(".inner").animate({
             top: '-100px'
         }, 2000);
         clicked = true;
     }
 });​

Just put another code line underneath the first and it will animate them in order

$(document).ready(function() {
    $('.try').click(function() {
        $(".inner").animate({
            top: '-=100px'
        }, 2000);
        $(".inner").animate({
            top: '+=100px'
        }, 2000);
    });
});
发布评论

评论列表(0)

  1. 暂无评论