Javascript 如何获得精确的offsetLeft和offsetTop值?

Javascript 如何获得精确的offsetLeft和offsetTop值?,javascript,html,Javascript,Html,HTML <body> <div class="col-lg-8 text-center"> <div class="well col-lg-12" id="TwoPlayer"> <p><a class="btn btn-primary btn-lg right" id="backButtonTP1">Home</a></p>

HTML

 <body>     
 <div class="col-lg-8 text-center"> 
        <div class="well col-lg-12" id="TwoPlayer">
            <p><a class="btn btn-primary btn-lg right" id="backButtonTP1">Home</a></p>    
            <button id="new1" class="btn btn-primary btn-lg pull-left">New Game</button>
            <canvas id="tttBoard"  width="500px" height="500px">Your browser does not seem to support the canvas element. Try Firefox or Chrome!</canvas>
            <script>window.TicTacToe.drawBoard();window.TicTacToe.drawMark(col,row);</script>
            </div>
        </div>
</body>

当我把这个双人div放在另一个应用引导的div中时,它给出了错误的offset top和offset left值。如果我将div放置在父div的外部,则正确显示“偏移顶部”和“偏移左侧”值。原因可能是什么。帮我解决这个问题。谢谢。

偏移量始终相对于其父对象。因此,如果您想要相对于文档的偏移量,则需要获取其所有祖先的偏移量。我没有测试,只是写在这里

var f = e;
var offsetLeft = 0;
var offsetTop = 0;

while( ( f = f.parentNode.tagName.toLowerCase() ) != 'html' ){
  var gbcr = f.getBoundingClientRect();
  offsetLeft += Math.round(gbcr.left);
  offsetTop  += Math.round(gbcr.top);
}
如果这是可行的,那么它应该给你相对于身体的偏移量

如果只需要相对于其父元素的偏移量,则只需使用while的主体

var boundingRectangle = e.getBoundingClientRect();
var offsetLeft = Math.round(boundingRectangle.left);
var offsetTop = Math.round(boundingRectangle.top);

这里提到的标记名是什么?它将检索节点的标记名。例如,如果您的节点是div,那么它将返回“div”
var boundingRectangle = e.getBoundingClientRect();
var offsetLeft = Math.round(boundingRectangle.left);
var offsetTop = Math.round(boundingRectangle.top);