开发者

Ways of determining the position of an element on a page using Jquery

I am using offset() to get the current position of an image just after a UL. I am positing the image absolutely so that it hangs off the first li as a poi开发者_如何转开发nter. When any li is clicked i want the image to slide to that particular li.

The first time i click on a li it slides to the centre of the page. But then when i make subsequent clicks it moves the proper distance, only in the centre of the page because its already been set incorrectly.

I hope this makes sense.

Here is my HTML

<ul id="llist">
    <li class="t current"><a href="#"><span>solutions</span></a><img src="images/bg-tab-leader-arrow.png" width="24" height="53" title="pointer" class="pointer" /></li>
    <li class="m"><a href="#"><span>credit mangement solutions</span></a></li>
    <li class="b"><a href="#"><span>third party additions</span></a></li>
</ul>

and my JS to date (which also nicely fades out tabs)

$('#llist li').click(function() {
    var thisTop = $(this).offset().top;
    $('.pointer').animate( {'top': thisTop} );
    return false;
});

CSS:

#subheader { position:relative; }
#subheader #llist { float:left; width:286px; margin:0 0 18px 0; padding:0; list-style:none; }
#subheader #llist li { color:#005474; line-height:68px; height:70px; background:url(../images/bg-tab-leader.png) no-repeat; position:relative; }
#subheader .pointer { z-index:1000; position:absolute; top:9px; right:-22px; }

Any ideas on why this positions itself in the centre of the page when i first click instead of just sliding it to the relative LI would be greatly appreciated.


I'm a little bit confused by this line:

var thisTop = $('#llist').offset().top;

...since it gets the top position of the llist, not the <li> that was clicked.

If I change it to:

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

...it seems to work fine.

Example: http://jsfiddle.net/patrick_dw/hxAzW/1/


EDIT:

The issue may be that you need to use .position() instead of .offset(), so that it uses the relative position of the <li> within the container.

EDIT:

Also looks like you need to give relative positioning to the container llist.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜