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>
JAVASCRIPT
if (e.pageX != undefined && e.pageY != undefined)
{
x = e.pageX;
y = e.pageY;
console.log(x,y);
}
else
{
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
x -= elem.offsetLeft;
y -= elem.offsetTop;
当我将这两个玩家div放在另一个应用了bootstrap的div中时,它会给出错误的offset-top和offset-left值。如果我将div放在父div之外的offset-top和offset-left值正确显示。这可能是原因。帮我解决这个问题。感谢。
答案 0 :(得分:0)
偏移量始终相对于它的父级。因此,如果您想要相对于文档的偏移量,您需要获得其所有祖先的偏移量。我没有测试它,只是在这里写下来。
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);