jquery Get click on the absolute position of the control simple instance _jquery

Source: Internet
Author: User

In the process of using jquery, you want to get the absolute position of the current click Input to show a div,jquery itself provides offset and position this two methods, but position official explanation is relative to the offset Parent, you can see is for the Father node, and offset official explanation relative to the document, seemingly using offset can be directly absolute positioning. However, if there is a nested div in the Web page, top and left overlap, so this time if you want to locate a new div to remove the Father node offset, jquery provides offsetparent this method

Therefore, the following code can display an absolutely positioned div below the click of a control

$ (' #id '). Click (Function (event) { 
  var curleft = $ (event.target). Offset (). Left; 
  var curtop = $ (event.target). Offset (). top+$ (Event.target). Outerheight (); 
  var obj = $ (event.target); 
  obj = Obj.offsetparent (); 
  Gets the absolute position of the control while 
  (Obj.attr (' TagName '). toLowerCase ()!= ' body ') { 
  curleft =curleft-obj.offset (). Left; 
    Curtop =curtop-obj.offset (). Top; 
    obj = Obj.offsetparent (); 
  } 
  $ (' #div '). CSS (' top ', curtop+ ' px '). CSS (' left ', curleft+ ' px '); 

The above is a small series of jquery for everyone to get click on the absolute location of the control of a simple instance of all the content, I hope that we support the cloud-Habitat Community ~

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.