My issue is that I have 2 <div>
s, containing the same elements. These elements are placed below each other. Upon setting the elements' top
and left
property to the value provided by .offset()
, then setting the position
to absolute
after this, the elements' offset values are both returned as 0. Why?
$(function(){ $('[data-distance]').each(function(i,el){ var $this = $(el), offset = $this.offset(); $this.css(offset); $this.css('position','absolute'); }); });
body { margin: 0; height: 1000px; font-family: arial; } h1 { margin: 0 0 10px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div data-distance="1"> <h1>Text</h1> <p>Assssssdddddddasdasdasdasdasdasdasdsda</p> </div> <div data-distance="0.5"> <h1>Text</h1> <p>Assssssdddddddasdasdasdasdasdasdasdsda</p> </div>
It's 0
because when the first iteration of the loop happens it sets the position of the first $('[data-distance]')
to absolute, so when the second iteration happens, the first element is at position top: 0
, left: 0
. Because of this, the attribute position: absolute
should be added after finding the offset of all matched elements.
It should be like this http://jsfiddle.net/vp7jt2xj/
$('[data-distance]').each(function (i, el) {
var $this = $(el),
offset = $this.offset();
$this.css(offset);
});
$('[data-distance]').css('position', 'absolute');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.