开发者

How to move a div to a certain position on the page using jQuery?

开发者 https://www.devze.com 2023-03-24 14:55 出处:网络
I\'m trying to get the red div to come up and sit under the click me link when that link is clicked. $(\'.clickMe\').click(function() {

I'm trying to get the red div to come up and sit under the click me link when that link is clicked.

$('.clickMe').click(function() {

    var pos = $(this).offse开发者_StackOverflowt().top;           

    $('.myDiv').animate({
        marginTop: '-'+pos+'px',
    }, 1000 );       

}); 

<a href="" class="clickMe">Click Me</a>
<br /><br /><br /><br /><br /><br /><br /><br />
<div style="position: absolute; border: 1px solid red; height: 50px; width: 50px" class="myDiv"></div>

Here's my failed attempt:

http://jsfiddle.net/SWqmb/4/

How do I get this to work?


Try this instead, animating the top property is probably a better choice, negative margins can have undesirable effects:

$('.clickMe').click(function(e) {

    e.preventDefault();

    var pos = $(this).offset().top;           

    $('.myDiv').animate({
        top: pos + $(this).height()
    }, 1000 );

});   

Demo: http://jsfiddle.net/SWqmb/6/


This should work. http://jsfiddle.net/SWqmb/8/

But i think is not the best way to do it.

0

精彩评论

暂无评论...
验证码 换一张
取 消