Javascript to obtain the width and height of the hidden dom

Source: Internet
Author: User

A hidden DOM cannot be obtained in width. If you want to obtain it, use the following method:

First, clone a DOM, set position: absolute, set top to a relatively large negative value, and display it. Finally, retrieve the width and height of the DOM and remove it.

The Code is as follows:

Copy to ClipboardReference: [www.bkjia.com] function getCss (elem, css ){
If (window. getComputedStyle ){
Return window. getComputedStyle (elem, null) [css];
} Else if (elem. currentStyle ){
Return elem. currentStyle [css];
} Else {
Return elem. style [css];
}
}
Function getWH (dom ){
Var get = function (elem ){
Var wh = {};
'Width height'. replace (/[^] +/g, function (I ){
Var a = I. toLowerCase ();
Wh [a] = elem ['offset' + I] | elem ['client' + I];
});
Return wh;
};
If (getCss (dom, 'display') = 'None '){
Var nDom = dom. cloneNode (true );
NDom. style. position = 'absolute ';
NDom. style. top = '-3000px ';
NDom. style. display = 'block ';
Document. getElementsByTagName ('body') [0]. appendChild (nDom );
Var wh = get (nDom );
NDom. parentNode. removeChild (nDom );
Return wh;
}
Return get (dom );
}
// Test
Console. log (getWH (document. getElementById ('content ')));
Var domA = document. createElement ("a"), _ ostyle = "position: absolute; z-index: 999999; width: 92px; height: 22px; position: absolute; display: none ;";
DomA. setAttribute ("style", _ ostyle );
DomA.style.css Text = _ ostyle;
DomA. setAttribute ("href", "javascript: void (0 );");
Document. getElementsByTagName ('body') [0]. appendChild (o );
Console. log (getWH (domA ));

There are other better methods.

Source: http://www.js8.in/

Related Article

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.