使用 jQuery.offet()获取并设置位置

如何用 jQuery.offset方法获取和设置元素的位置?

假设我有一个 div layer1和另一个 layer2。我怎样才能得到 layer1的位置,并设置相同的位置为 layer2

247960 次浏览
//Get
var p = $("#elementId");
var offset = p.offset();


//set
$("#secondElementId").offset({ top: offset.top, left: offset.left});

It's doable but you have to know that using offset() sets the position of the element relative to the document:

$('.layer1').offset( $('.layer2').offset() );

I recommend another option. jQuery UI has a new position feature that allows you to position elements relative to each other. For complete documentation and demo see: http://jqueryui.com/demos/position/#option-offset.

Here's one way to position your elements using the position feature:

var options = {
"my": "top left",
"at": "top left",
"of": ".layer1"
};
$(".layer2").position(options);

Here is an option. This is just for the x coordinates.

var div1Pos = $("#div1").offset();
var div1X = div1Pos.left;
$('#div2').css({left: div1X});
var redBox = $(".post");


var greenBox = $(".post1");


var offset = redBox.offset();


$(".post1").css({'left': +offset.left});
$(".post1").html("Left :" +offset.left);

http://jsfiddle.net/va836/159/