问题
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