简体   繁体   中英

How to get the position of a moving object continuosly in a html page using javascript?

我使用Javascript在我的html页面中创建了一个移动对象,我应该每次在块中移动时返回x和y坐标。我该怎么做?

You can use the getBoundingClientRect() method for the relevant element. Try this:

var element = document.getElementById("myDivId");
console.log(element.getBoundingClientRect());

It will give you coordinates of all of it's corners from the top left corner. And add an window.setInterval() callback to sample it's location and do what ever logic you want when it is changed.

您可以使用.offset()jQuery函数来获取元素的当前坐标

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function()
{
       var a =  $("#divTestBox1").animate(
                {
                        "left" : "200px",
                        "top"  : "200px",
                },5000,function(event){

                    var x = $("#divTestBox1").offset().left;


                    var posx = $('#pos').html('left:'+x +'px');


                }
        );

});
</script>
<div id="divTestBox1" style="position: absolute;">rachana_sharma003</div>
<div id="pos"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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