问题
I'm using jquery's append() method, to add elements (div) to parent element (div as well).
When calling the offset function of the parent div, i'm getting it's relative position just fine. When i'm calling the child element, i'm getting 0 as its relative position (top and left)
Anyone have any idea how to solve this problem? How can I get the position of dynamically added div?
var $grid = $('#myDiv');
$grid.empty()
$grid.append("<div id="newDiv">...")
console.log($("#newDiv").position())
Output: top: 0 left: 0
(it shows me the current scroll bar offset from the top)
回答1:
The returned value is correct. From the jquery documentation for .position():
Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
Unless it has styles, it's always going to be at 0,0.
You might want to use .offset() instead.
回答2:
Does this help you? (Run it directly below)
for(i=0;i<5;i++){
$(".parent").append("<div class='child'></div>");
}
$("div.child").each( function(){
var $this=$(this);
var top = $this.position().top;
console.log(top);
$this.text( "Distance from top : " + top )
})
div.child{
height : 20px;
outline: blue solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent"></div>
回答3:
This is an example of whan i'm trying to do
var $parent = $("parentDiv")
$parent.empty()
for(i=0;i<5;i++){
$parent.append("<div class='child'></div>");
}
$("div.child").each( function(){
var $this=$(this);
var top = $this.position().top;
console.log(top);
$this.text( "Distance from top : " + top )
})
div.child{
height : 20px;
outline: blue solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parentDiv"></div>
回答4:
I'm starting to figure this out
the problem is probably caused by backbone.js, i'm using data-cid to retrieve the elements, and these attributes from some reason are not sowing up (or as 0)
回答5:
You should try
var $grid = $('#myDiv');
$grid.empty()
var new_div = $grid.append("<div id='newDiv'>...")
console.log($(new_div).position())
As "new_div" variable has the appended element returned by the append function.
来源:https://stackoverflow.com/questions/28408021/jquery-append-element-position-always-0