JavaScript. Absolute position of <li> element relative to browser bounds?
How to know the absolute position of <li>
element relative to browser bounds?
<html>
<body style="overflow: hidden">
<div ID="Ticker" style="position:absolute; white-space: nowrap;">
<ol style="list-style-type:decimal; ">
<li style="float: left; width: 100px; padding: 2px 0px;">Test</li>
<li style="float: left; width: 100px; padding: 2px 0px;">Test</li>
<li ID="TargetElem" style="float: l开发者_StackOverflow中文版eft; width: 100px; padding: 2px 0px;">Test</li>
<li style="float: left; width: 100px; padding: 2px 0px;">Test</li>
<li style="float: left; width: 100px; padding: 2px 0px;">Test</li>
<li style="float: left; width: 100px; padding: 2px 0px;">Test</li>
<li style="float: left; width: 100px; padding: 2px 0px;">Test</li>
</ol>
</div>
<script type="text/javascript" src="ticker.js" language="javascript"></script>
</body>
</html>
I need a way to know the left value of element <li>
with ID="TargetElem"
.
Borrowed from http://www.quirksmode.org/js/findpos.html...
// findPosition() by quirksmode.org
// Finds the **absolute** position of an element on a page
function findPosition(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
/*
* The loop continues until the object currently being investigated
* does not have an offsetParent any more. While the offsetParent is
* still there, it still adds the offsetLeft of the object to curleft,
* and the offsetTop to curtop.
*/
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return [curleft,curtop];
}
This function should work well in IE6, IE7, IE8, Safari, Firefox and Chrome but I haven't tested it thoroughly. Also, this article might be relevant for your needs...
- http://blog.stannard.net.au/2010/05/22/find-the-position-of-an-element-with-javascript/
I hope this helps.
Plain JS:
var elem = document.getElementById('TargetElem');
var left = elem.offsetLeft;
JS Fiddle demo.
jQuery offers the following option:
The offset()
of the element gives the position of the top-left corner of the element in terms of its distance, in pixels, from the top-left corner of the window.
To find the x-offset of the element:
$('#TargetElem').offset().left
To find the y-offset of the element:
$('#TargetElem').offset().top
JS Fiddle demo.
var elem = document.getElementById('TargetElem'),
left = elem.offsetLeft;
Assuming the <li> is offset relative to the window, this will give you the correct value.
精彩评论