【发布时间】:2013-12-30 00:03:39
【问题描述】:
我将如何使用 JavaScript 或 jQuery 计算 div x 和 y 坐标的左下角。
例如,您如何找到绿色框的左下角? HTML:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<body>
<div id="result">Click an element.</div>
<p>
This is the best way to <span>find</span> an offset.
</p>
<div class="abs">
</div>
CSS:
p {
margin-left: 10px;
color: blue;
width: 200px;
cursor: pointer;
}
span {
color: red;
cursor: pointer;
}
div.abs {
width: 50px;
height: 50px;
position: absolute;
left: 220px;
top: 35px;
background-color: green;
cursor: pointer;
}
JavaScript:
$( "*", document.body ).click(function( event ) {
var offset = $( this ).offset();
event.stopPropagation();
$( "#result" ).text( this.tagName +
" coords ( " + offset.left + ", " + offset.top + " )" );
});
链接到 JSFiddle 示例:http://jsfiddle.net/hfjVQ/
【问题讨论】:
标签: javascript jquery