问题描述:

I wanted to create a simple dotted underline animation for a menu bar of mine , so i wrote the following HTML:

<nav role="navigation" class="navigation">

<ul class="nav-listed-links">

<li class="active"><a href="">Home</a></li>

<li><a href="">About</a></li>

<li><a href="">Our Potfolio</a></li>

<li><a href="">History</a></li>

<li><a href="">Contact US</a></li>

<li class="underline"></li>

</ul>

</nav>

And the following JS code to make the underline move.

JS:

$('.nav-listed-links > li > a').hover(function() {

var offset = ($(this).offset().left - 0),

width = $(this).outerWidth();

$('.underline').addClass('on');

$('.underline').css({

left: offset,

width: width

});

}, function() {

$('.underline').removeClass('on');

});

The smooth animation is CSS transitions, FIDDLE HERE.

Ok so now lets zero down on the problem , In the JS code i am try to get how far off the <a> is from the left of the document and so i have the following code:

var offset = ($(this).offset().left - 0)

Yet the underline is a bit off from where the start of the <a> tag is, see screenshot below:

Why is this happening. I am sure this is something silly , but i really have't been able to figure this out for the life in me.

网友答案:

With offset() you

retrieves the current position relative to the document

Therefore with the default margin of the body you have that extra gap.

I suggest the use of position() to avoid any problems, since the underline is relative to the ul container :

retrieve the current position of an element relative to the offset parent

var offset = $(this).position().left,

Updated Fiddle


Reference Position()

网友答案:

This is just because of the margin, the body have in the fiddle. Setting margin: 0 works perfect. Such margin you might be having on the outer elements also. You'll have to take those margins also.

Here is an updated JSFiddle with margin-left: 0px; on the body element: https://jsfiddle.net/w8unr0od/2/

相关阅读:
Top