


A handwritten javascript getStyle function compatible with various browsers (getting the style of an element)_javascript skills
There have always been many compatibility issues in getting the calculated style of HTML elements. There are some differences in each browser. Firefox and webkit (Chrome, Safari) support the W3C standard method: getComputedStyle(), while IE6/7/ 8 does not support the standard method but has private properties to implement it: currentStyle, both IE9 and Opera support it. With these two methods and attributes, most requirements can basically be met.
var getStyle = function( elem, type ){
return 'getComputedStyle' in window ? getComputedStyle(elem, null)[type] : elem.currentStyle[type];
};
But for adaptive width and height, you cannot get the calculated value using currentStyle. You can only return auto, and getComputedStyle() can return the calculated value. There are several ways to solve this problem. What I thought of before was to subtract the padding value from clientWidth/clientHeight, so that the calculated width and height can be obtained in browsers that do not support the standard method. A few days ago, I saw that Situ Zhengmei used another method, using the getBoundingClientRect() method to get the position of the element on the page, and then subtracting right from left is the width, and bottom minus top is the height. I made some small modifications to his code, and the final code is as follows:
var getStyle = function( elem, style ){
return 'getComputedStyle' in window ?
getComputedStyle( elem, null )[style] :
function(){
style = style.replace( /-(w)/g, function( $, $1 ){
return $1.toUpperCase();
});
var val = elem.currentStyle[style];
if( val === 'auto' && (style === "width" || style === "height") ){
var rect = elem.getBoundingClientRect();
if( style === "width" ){
return rect.right - rect.left 'px';
}else{
return rect.bottom - rect.top 'px';
}
}
return val;
}();
};
// Call this method
var test = document.getElementById( 'test' ),
// Get the calculated width
tWidth = getStyle( test, 'width' );
New question, if the width or height of the element uses em or % units, the value returned by getComputedStyle() will automatically change em or % into px units, but currentStyle will not, and if it is font- size uses em as the unit, and returns 0em under Opera. Opera is really scary!
Later, I found some unexpected compatibility issues during use. Today I optimized the original code and dealt with some common compatibility issues.
In JavaScript, "-" (dash or hyphen) represents a minus sign, and in CSS, many style attributes have this symbol, such as padding-left, font-size, etc., so If the following code appears in javascript, it is an error:
The correct writing should be:
Here you need to remove the underline in CSS and capitalize the letters immediately following the underline, commonly known as "camel case" The writing method, whether you use javascript to set or get the CSS style of the element, should be written in camel case. However, many novice friends who are familiar with CSS but not familiar with javascript will always make this low-level mistake. Using the advanced usage of replace can easily replace the underscore in the CSS attribute with camel case writing.
return $1.toUpperCase();
});
For float, it is a reserved word in JavaScript. There are other alternative ways to set or get the float value of an element in JavaScript. In standard browsers, it is cssFloat, and in IE6/7/8, it is styleFloat. .
If top, right, bottom, and left do not have an explicit value, some browsers will return an auto when obtaining these values. Although the auto value is a legal CSS attribute value, it is by no means what we want. The result should be 0px.
To set the transparency of elements in IE6/7/8, you need to use filters, such as: filter:alpha(opacity=60). For standard browsers, just set opacity directly. IE9 supports both writing methods. I Compatibility has also been implemented for obtaining the transparency of elements. As long as you use opacity, you can obtain the transparency values of all browser elements.
Getting the width and height of elements in IE6/7/8 has been introduced in the previous article, so I won’t repeat it here. Another thing to note is that if the style of the element is written using style inline, or the style attribute has been set using JavaScript, you can use the following method to get the calculated style of the element:
var height = elem.style.height;
This method is faster than reading the attribute value in getComputedStyle or currentStyle, and should be used first. Of course, the prerequisite is that the style is set by inline writing (using javascript to set the inline style is also set). The optimized final code is as follows:
var getStyle = function( elem, p ){
var rPos = /^(left|right|top|bottom)$/,
ecma = "getComputedStyle" in window,
// Convert the underscore to camel case such as: padding-left => paddingLeft
p = p.replace( /-(w)/g, function( $, $1 ){
return $1.toUpperCase();
});
// Process float
p = p === "float" ? ( ecma ? "cssFloat" : "styleFloat" ) : p;
return !!elem.style[p] ?
elem.style[ p] :
ecma ?
function(){
var val = getComputedStyle( elem, null )[p];
// Handle the case where top, right, bottom and left are auto
if( rPos.test(p) && val === "auto" ){
return "0px";
}
return val;
}() :
function() {
var wirelesscasinogames.com val = elem.currentStyle[p];
// Get elements in IE6/7/8 The width and height in
if( (p === "width" || p === "height") && val === "auto" ){
var rect = elem.getBoundingClientRect();
return ( p === "width" ? rect.right - rect.left : rect.bottom - rect.top ) "px";
}
// Get elements in IE6/7/8 Transparency in
if( p === "opacity" ){
var filter = elem.currentStyle.filter;
if( /opacity/.test(filter) ){
val = filter .match( /d / )[0] / 100;
return (val === 1 || val === 0) ? val.toFixed(0) : val.toFixed(1);
}
else if( val === undefined ){
return "1";
}
}
// Handle the case where top, right, bottom and left are auto
if ( rPos.test(p) && val === "auto" ){
return "0px";
}
return val;
}();
};
The following is an example call:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
