【问题标题】:Calculate bottom left corner of a div计算div的左下角
【发布时间】: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


    【解决方案1】:

    左下角坐标将是偏移顶部位置,加上元素的高度。您可以使用以下内容:

    $(this).offset().top + $(this).outerHeight(true);
    

    我们使用outerHeight()true 参数,因为它将计算元素的实际外部高度,包括边框和可能应用的任何边距。

    所以您的代码将如下所示:

    $("*", document.body).on('click', function(e) {
        e.stopPropagation();
        var offset = $( this ).offset();
    
        $( "#result" ).text(this.tagName+" coords ("+offset.left+", "+offset.top+", "+(offset.top + $(this).outerHeight(true))+")");
    });
    

    jsFiddle Demo

    【讨论】:

    • @user1839601 没问题!
    • 哎呀,那不是只计算左下点的Y轴吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 2020-06-17
    相关资源
    最近更新 更多