使用 jQuery .offset() 获取和设置位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4613261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:34:35  来源:igfitidea点击:

Get and set position with jQuery .offset()

jquery

提问by Denise

How to get and set the position of an element with the jQuery .offsetmethod?

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

Let's say I have a div layer1and another layer2. How can I get the position of layer1and set the same position to layer2?

假设我有一个 divlayer1和另一个layer2. 如何获取 的位置layer1并将相同的位置设置为layer2

回答by Steve

//Get
var p = $("#elementId");
var offset = p.offset();

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

回答by KSev

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.

我推荐另一种选择。jQuery UI 有一个新的位置功能,允许您相对于彼此定位元素。有关完整的文档和演示,请参阅: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);

回答by Amjad Masad

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

这是可行的,但您必须知道 usingoffset()设置元素相对于文档的位置:

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

回答by hillspro

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

这是一个选项。这仅适用于 x 坐标。

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

回答by Chirag Suthar

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/

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