How to get the mouse's relative position in the div

Source: Internet
Author: User
Tags gety relative

  How to get the mouse in the relative position in the div, in fact, is very simple, there is a good example, interested friends can refer to the following

  Code as follows: <HEAD>  <TITLE> js get div relative coordinates </TITLE>  <script type= "Text/javascript" > <!--  function GetX (obj) {  var parobj=obj;  var left=obj.offsetleft;  while (parobj= parobj.offsetparent) {  left+=parobj.offsetleft; }  return left; }    function GetY (obj ) {  var parobj=obj;  var top=obj.offsettop;  while (parobj = parobj.offsetparent) {  top+= parobj.offsettop; }  return top; }    function Displaycoord (event) {  var top,left,odiv;   Odiv=document.getelementbyid ("demo");  top=gety (odiv);  left=getx (odiv);  document.getElementById ("mp_x"). InnerHTML = (event.clientx-left+document.documentelement.scrollleft) -2+ "px";   document.getElementById ("mp_y"). InnerHTML = (event.clienty-top+document.documentelement.scrolltop) -2+ "px";  } //--></script>  </HEAD>    <body style= "margin:40px" Margin:40px; " >  <div style= "background-color: #000000; color: #0011FF; width:300px;height:300px;position:absolute;top : 80px;left:90px;margin:0px; border:0px "Id=" demo "onmousemove=" Displaycoord (event) >  I am div, tested, 2PX error ...  </div>  The current mouse coordinates are:  x:<span id= "mp_x" ></span>  y:<span id= "mp_y" ></span>  </body >  </BODY>    </HTML>      If not, you can try the     document.documentelement.scrollleft    Replacement     document.body.scrollleft   

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.