最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get element's horizontal and vertical position with javascript - Stack Overflow

programmeradmin4浏览0评论

I made a script that moves my "character" (element ID="character") to where I click. But I need to get it's position so I can make it "walk" to where I click instead of it just appearing there.

This is my code:

<html>
<head>
<script type="text/javascript">
function showCoords(evt){
  document.getElementById("character").style.left = evt.pageX;
  document.getElementById("character").style.top = evt.pageY;
}
</script>
</head>

<body onmousedown="showCoords(event)">
<div id="character" style="position: absolute; top: 100px; width: 80px; height: 40px; background:black;"> Char </div>
</body>
</html>

Basically I just want to retrieve the element's horizontal and vertical position at the beginning of my function. So I can later use those variables. How do I do it?

Thanks

I made a script that moves my "character" (element ID="character") to where I click. But I need to get it's position so I can make it "walk" to where I click instead of it just appearing there.

This is my code:

<html>
<head>
<script type="text/javascript">
function showCoords(evt){
  document.getElementById("character").style.left = evt.pageX;
  document.getElementById("character").style.top = evt.pageY;
}
</script>
</head>

<body onmousedown="showCoords(event)">
<div id="character" style="position: absolute; top: 100px; width: 80px; height: 40px; background:black;"> Char </div>
</body>
</html>

Basically I just want to retrieve the element's horizontal and vertical position at the beginning of my function. So I can later use those variables. How do I do it?

Thanks

Share Improve this question edited May 3, 2011 at 2:39 lisovaccaro asked May 3, 2011 at 2:18 lisovaccarolisovaccaro 34.1k99 gold badges271 silver badges423 bronze badges 3
  • I'm confused: does document.getElementById("character").style.left and .top not give you those values to start with? – Gordon Seidoh Worley Commented May 3, 2011 at 2:23
  • It depends on the position property of that element. For example, if its value is relative, then the left and top properties (if ever defined) will tell you just how many pixels the element is relative to its parent. – Nicolás Ozimica Commented May 3, 2011 at 2:34
  • I thought document.getElementById("character").style.left was only to change it's position. How can I print that value? That would answer my question. Thanks – lisovaccaro Commented May 3, 2011 at 2:37
Add a ment  | 

2 Answers 2

Reset to default 6

If you only need this to work in reasonably modern browsers, then document.getElementById("character").getBoundingClientRect() will have left and top properties that give you the offsets from the viewport.

Using MooTools you can get the position of an element with:

$('element').getPosition(); // returns {x: 100, y: 500};

MooTools docs: Element Method: getPosition

发布评论

评论列表(0)

  1. 暂无评论