在jquery中获取子div的位置

时间:2017-03-17 05:48:29

标签: jquery html css

我想得到孩子div' test1'的位置。我想从父div获得左侧位置。父div和子div之间的距离是< 10px'我想得到10像素。现在它打印140px(从屏幕起始位置计算)。



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:100%">
  <div style="width:250px;background-color:red;padding:10px;margin:auto auto;height:100px" class="testParent">
    <div class="test1">one</div>
    <div class="test1">two</div>
    <div class="test1">three</div>
    <div class="test1">three</div>
    <div class="test1">three</div>
  </div>
</div>
&#13;
public abstract class BaseFragment<VS extends ViewState> extends Fragment {

    // @Icicle
    VS mViewState;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Icepick.restoreInstanceState(this, savedInstanceState);

        if (mViewState == null) mViewState = createViewState();

        mViewState.setSavedInstance(savedInstanceState != null);

    }
&#13;
return null;
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

position()添加到父元素,然后.position()将返回相对于父元素的位置。

  

jQuery(document).ready(function($) { $('.test1').click(function() { var p = $(this); var position = p.position(); console.log(position); }); });方法允许我们检索当前位置   元素相对于偏移父元素

<强> Source

&#13;
&#13;
.test1 {
  float: left;
  background-color: yellow;
  padding: 10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:100%">
  <div style="position:relative;width:250px;background-color:red;padding:10px;margin:auto auto;height:100px" class="testParent">
    <div class="test1">one</div>
    <div class="test1">two</div>
    <div class="test1">three</div>
    <div class="test1">three</div>
    <div class="test1">three</div>
  </div>
</div>
&#13;
list
&#13;
&#13;
&#13;