如何知道<li>
元素相对于浏览器边界的绝对位置?
<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: 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>
<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>
我需要一种方法来了解<li>
元素ID="TargetElem"
的左侧值。
答案 0 :(得分:5)
借鉴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];
}
此功能应该在IE6,IE7,IE8,Safari,Firefox和Chrome中运行良好,但我还没有彻底测试过。此外,本文可能与您的需求相关......
我希望这会有所帮助。
答案 1 :(得分:1)
普通JS:
var elem = document.getElementById('TargetElem');
var left = elem.offsetLeft;
jQuery提供以下选项:
元素的offset()
根据窗口左上角的距离(以像素为单位)给出元素左上角的位置。
要查找元素的x偏移量:
$('#TargetElem').offset().left
要查找元素的y偏移量:
$('#TargetElem').offset().top
答案 2 :(得分:0)
var elem = document.getElementById('TargetElem'),
left = elem.offsetLeft;
假设&lt; li&gt;相对于窗口偏移,这将为您提供正确的值。