简体   繁体   English

如何获取div的坐标?

[英]How do I get the coordinates of a div?

I have used jQuery UI library to drag divs within a web page. 我已经使用jQuery UI库在网页中拖动div。 While dragging, the div changes it's position and modifies CSS postion,top and left properties. 拖动时,div更改其位置并修改CSS位置,顶部和左侧属性。

My questions are: 我的问题是:

1) Is their a way in javascript to get the values of CSS properties and save on a variable(so that I can submit it to XML)? 1)是他们在javascript中获取CSS属性值并保存在变量中(以便我可以将其提交到XML)的一种方法吗? Those CSS properties are created on real time when dragging the divs. 这些CSS属性是在拖动div时实时创建的。

2) Can I at least read the new coordinates of the div on the webpage? 2)我至少可以阅读网页上div的新坐标吗?

My goal is to record those values so that when users logs in next time, their modified version of the web page is preserved. 我的目标是记录这些值,以便在用户下次登录时保留其修改后的网页版本。

To read the co-ordinates relative to the viewport, use offset() : 要读取相对于视口的坐标,请使用offset()

var offset = $('#someitem').offset();
console.log('top: '+offset.top+'; left: '+offset.left);

To read the co-ordinates relative to the nearest positioned ancestor, use position() : 要读取相对于最近定位的祖先的坐标,请使用position()

var pos = $('#someitem').position();
console.log('top: '+pos.top+'; left: '+pos.left);

To get CSS properties, just use the css() function: 要获取CSS属性,只需使用css()函数:

console.log($('someitem').css('top'));

you can easily get the offset of an element using jQuery. 您可以使用jQuery轻松获取元素的偏移量。

var offset = $("#some-element").offset();

// Alert the values
alert("top: " + offset.top+ "left: " + offset.left);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM