Jquery animate left is not working, what's wrong?

谁说胖子不能爱 提交于 2019-12-11 05:52:09

问题


I'm using jQuery's animate() and it just doesn't work. I'm trying to get a div to slide off another div that's containing it and has overflow:hidden. I've tried every combination of left on the animate and nothing. Just to make sure, I also tried changing the width of the div (gallery) and it does change the width, but not the left.

What am I doing wrong?

function an() {

  //$('#gallery').fadeOut();
  //$('#gallery').animate({left:'-=1000'},'slow');
  $('#gallery').animate({
    'left': '+=100px'
  }, 'slow');

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div align="center" style="position:relative; height:137px; overflow:hidden; width:1000px; border:3px solid #ff0000;">
  <div id="gallery" style="background-color:#033; width:100px; height:137px;"></div>
</div>
<a href="#" onclick="an(); return false;">test</a>

View on JSFiddle


回答1:


You should give the #gallery div a position:relative and then it works fine.

function an() {

  //$('#gallery').fadeOut();
  //$('#gallery').animate({left:'-=1000'},'slow');
  
  $('#gallery').animate({
    'left': '-=700px'
  }, 'slow');

}
#gallery {
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div align="center" style="position:relative; height:137px; overflow:hidden; width:1000px; border:3px solid #ff0000;">
  <div id="gallery" style="background-color:#033; width:100px; height:137px;"></div>
</div>
<a href="#" onclick="an(); return false;">test</a>

View on JSFiddle

By the way, you should avoid inline JavaScript (like onclick) and CSS whenever possible. Also, the align attribute was deprecated in HTML 4.01 and eliminated in HTML5.




回答2:


simply add:

style="position:relative;"

to the element that you want to move.

  • you don't have to add it to it's container div.
  • it will be relative to it's container and will move according to it's position.


来源:https://stackoverflow.com/questions/10522799/jquery-animate-left-is-not-working-whats-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!