简体   繁体   English

position是javascript或jquery中的数组

[英]position is an array in javascript or jquery

<div className="example" style="top:10;left:10"></div>  //array 1
<div className="example" style="top:100;left:100"></div>  //array 2
<div className="example" style="top:145;left:101"></div>  //array 3
<div className="example" style="top:120;left:150"></div>  //array 4
<div className="example" style="top:145;left:160"></div>  //array 5
<div className="example" style="top:10;left:120"></div>  //array 6
<div className="example" style="top:15;left:100"></div>  //array 7


<script>
var x = $(".example")[0].position();  //array 1 [0]
alert("Top: " + x.top + " Left: " + x.left);
</script>

I need to get the position of a certain div 我需要获得某个div的位置

but when I run the code I get error 但是当我运行代码时我得到了错误

VM163:1 Uncaught TypeError: $(...)[0].position is not a function(…) VM163:1未捕获的TypeError:$(...)[0] .position不是函数(...)

Try this: http://jsbin.com/liliwarogo/1/edit 试试这个: http : //jsbin.com/liliwarogo/1/edit

var x = $($(".example")[0]).position();  //array 1 [0]
alert("Top: " + x.top + " Left: " + x.left);

Basically, if you do $(".example")[0] it's not a jQuery element anymore, so position() doesn't exists. 基本上,如果您执行$(".example")[0]则它不再是jQuery元素,因此position()不存在。 I wrapped everything up in jQuery again, to get the position() function. 我再次将所有内容包装在jQuery中,以获得position()函数。

Of course, the optimal solution would be something like this: $(".example:eq(0)").position() 当然,最佳解决方案是这样的: $(".example:eq(0)").position()

This solution only use JavaScript. 此解决方案仅使用JavaScript。

var x = document.getElementsByClassName("example")[0].getBoundingClientRect();
alert("Top: " + x.top + " Left: " + x.left);

Here is the Jsbin example 这是Jsbin的例子

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

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