JavaScript gets page element specific location method

Source: Internet
Author: User

Getboundingclientrect (); This method gets the position of the left, top, right, and bottom of an element in the page relative to the browser window, and he returns an object, object, that has an attribute: Top,left,right,bottom Here, the top, the left and the CSS in the understanding is very similar, but Right,bottom and CSS understanding is a bit different, see schematic:

You can scroll through the red area to see the changes in the values after scrolling the scroll bar:

The full instance code is as follows

The code is as follows Copy Code
<body style= "width:2000px; height:1000px; " >
<div id= "Demo" style= "Position:absolute; left:518px; right:100px; width:500px; height:500px; Background: #CC0000; top:114px; " >demo in order to facilitate the direct use of absolute positioning of the elements </div>
</body>
<script>
document.getElementById (' demo '). Onclick=function () {
if (document.documentElement.getBoundingClientRect) {
Alert (' Left: ' +this.getboundingclientrect (). left)
Alert (' Top: ' +this.getboundingclientrect (). Top)
Alert (' Right: ' +this.getboundingclientrect (). right)
Alert ("Bottom:" +this.getboundingclientrect (). Bottom)
var x= this.getboundingclientrect (). Left+document.documentelement.scrollleft;
var Y = This.getboundingclientrect (). Top+document.documentelement.scrolltop;
Alert ("The location of the demo is X:" +x+; Y: "+y)
}
}
</script>

Note: Getboundingclientrect () is specific to IE, currently Ff3+,opera9.5+,safari 4, has supported this method.

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.