JS implementation drag sample code _ javascript tips-js tutorial

Source: Internet
Author: User
There are many ways to implement drag in JS. This article will show you how to implement the getBoundingClientRect () method. If you are interested, do not miss getBoundingClientRect () to get the location of the page element.

The Code is as follows:


Document.doc umentElement. getBoundingClientRect


This method returns an object to obtain the position of an element on the left, top, right, and bottom of the page relative to the browser window, that is, the offset pixel value of the top, left, right, and bottom borders of the element relative to the upper left corner of the browser window (note, not the upper left corner of the document area. This method is no longer Internet Explorer Only. FF3.0 + and Opera9.5 + support this method. It can be said that the efficiency can be greatly improved in obtaining the page element location, therefore, getting the offset of an element on the page relative to the browser window becomes a useful place for getBoundingClientRect. According to an article, it's awsome, so handsome =. = Because you don't have to worry about offset, pagex, clientx, and so on. In earlier versions of Opera and Firefox, the absolute position of elements on the page must be obtained through loops.


Sample Code:

The Code is as follows:






Demo



Demo directly uses absolute positioning elements for convenience




Script
Document. getElementById ('Demo'). onclick = function (){
If (document.doc umentElement. 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.doc umentElement. scrollLeft;
Var Y = this.getboundingclientrect().top?document.doc umentElement. scrollTop;

Alert ("the location of the Demo is X:" + X + "; Y:" + Y)
}
}
Script

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.