Home Web Front-end JS Tutorial ppk talks about JavaScript style attributes_javascript skills

ppk talks about JavaScript style attributes_javascript skills

May 16, 2016 pm 06:59 PM
javascript style

In fact, all seven sample scripts use some form of CSS modification. For example, "Form Validation" changes the style of an erroring form field, and "XMLHTTP Speed ​​Tester" uses animation (in fact, changing a style multiple times in a short period of time) to draw the user's attention to speed data (and, To be honest, this is a bit of a fancy effect). Drop-down menus show and hide menu items by changing styles. These changes all have the same purpose: to draw the user’s attention to these elements.

JavaScript has the following 4 ways to modify CSS:

l Modify the style attribute of the element (element.style.margin='10%');

l Change the element class or id (element.className='error'), the browser will automatically apply the styles defined on the new class or id;

l writes new CSS instructions to the document (document. write('');

l Change the style sheet of the entire page.

Most CSS change scripts use the method of modifying the style attribute or changing the class or id of the document. The .write method is only suitable for certain situations to enhance the accessibility of the page. Finally, we rarely change the entire style sheet, because not all browsers support this, and usually you only want to change something.

Anyway, I use all 4 methods in the example script. We will look at each of these methods and where they are applicable in this chapter. style attribute

The original and most well-known way to modify CSS is to access their inline styles through the style attribute owned by all HTML elements. The style object contains a corresponding one for each inline CSS declaration. Property. If you want to set the CSS property margin of an element, use element.style.margin. If you want to set its CSS property color, use the element.style.color JavaScript property.

Inline Styles

Remember: The style attribute of an HTML element gives us access to the inline styles of that element.

Let’s review some CSS. Theory. CSS provides 4 ways to define style sheets for elements. You can use inline styles, that is, write your CSS directly in the style attribute of the HTML tag. 🎜>
In addition, you can embed, link in or import style sheets regardless of the method used, because inline styles are more explicit than any other form of style, inline styles can override those that are embedded, linked in or imported. Styles defined in the page's stylesheet. Because the style attribute has access to these inline styles, it can always override other styles.

However, when you try to read. You may encounter problems when retrieving styles:

Text


p#test {

margin: 10%;

}


alert(document.getElementById('test').style.margin);

The test paragraph does not contain any inline styles, margin: 10% is defined in a In an embedded (or linked, or imported) style sheet, it is impossible to read it from the style attribute. The pop-up warning box appears empty.

In the next example, the popup alert box will display the return result "10%" because the margin is now defined as an inline style:


Text


alert(document.getElementById('test').style.margin);

So, the style attribute is best suited for setting styles, but not so useful for getting them. Later we will discuss ways to obtain styles from style sheets embedded in the page, linked in, or introduced.

Dash

Many CSS property names contain a dash, such as font-size. However, in JavaScript, the dash represents minus, so it cannot be used in property names. This will give an error:

element.style.font-size = '120%';

This is asking the browser to subtract (undefined) from element.style.font ) variable size? If = '120%' what does it mean? Instead, browsers expect a camelCase property name:

element.style.fontSize = '120%';

The general rule is to remove all elements from CSS property names dash, and the characters after the dash become uppercase. In this way, margin-left becomes marginLeft, text-decoration becomes textDecoration, and border-left -style becomes borderLeftStyle.

Units

Many numeric values ​​in JavaScript require a unit, just like when they are declared in CSS. What does fontSize=120 mean? 120 pixels, 120 points or 120%? The browser doesn't know this, so it doesn't do anything. To clarify your intent, units are a must.

Take the setWidth() function as an example. It is one of the core programs that implements the animation effect of "XMLHTTP Speedometer":

[XMLHTTP Speedometer, lines 70-73]

function setWidth(width) {

if (width
document.getElementById('meter').style.width = width 'px';

}

This function takes over a value and will change the width of the meter to this new value. After a safety check to ensure that the value is greater than 0, set the element's style.width to this new width value. Add 'px' at the end because otherwise the browser might not know how to interpret the value and do nothing.

Don't forget 'px'

Forgetting to append a 'px' unit after width or height is a common CSS modification error.

In CSS quirks mode, adding 'px' is not necessary because browsers follow the old rules and treat unitless values ​​as pixel values. This isn't a problem per se, but many web developers get into the habit of changing width or height values ​​and then forgetting to add units, which causes problems when they work in CSS strict mode.

Get style

Warning: The following content has browser compatibility issues.

As we have seen, the style attribute cannot read styles set in style sheets that are embedded, linked, or imported into the page. But because web developers sometimes need to read these styles, both Microsoft and the W3C provide ways to access non-inline styles. Microsoft's solution only works under Explorer, while the W3C standard works under Mozilla and Opera.

Microsoft's solution is the currentStyle property, which works exactly like the style property, except for two things:

l It has access to all styles, not just inline styles, so It reports the style actually applied to the element;

l It is read-only and you cannot set styles through it.

For example:

var x = document.getElementById('test');

alert(x.currentStyle.color);

Now the dialog pops up The box displays the element's current color style, regardless of where it is defined.

The W3C's solution is the window.getComputedStyle() method, which works in a similar but more complex syntax:

var x = document.getElementById('test');

alert(window.getComputedStyle(x,null).color);

getComputedStyle() always returns a pixel value, although the original style may be 50em or 11%.

As before, when we encounter incompatibilities, some code branches are needed to satisfy all browsers:

function getRealStyle(id,styleName) {

var element = document.getElementById(id);

var realStyle = null;

if (element.currentStyle)

realStyle = element.currentStyle[styleName];

else if (window.getComputedStyle)

realStyle = window.getComputedStyle(element,null)[styleName];

return realStyle;

}

You can use this function as follows:

var textDecStyle = getRealStyle('test','textDecoration');

Remember getComputedStyle() will always return a pixel value, and currentStyle Keep the units originally defined in the CSS.

Abbreviation style

Warning The following content has browser compatibility issues.

Whether you obtain inline styles through the style attribute, or obtain other styles through the functions just discussed, you will encounter problems when you try to read abbreviated styles.

Look at the definition of this border

Text



Since this is an inline style, you would expect this line of code to work:

alert(document.getElementById('test').style.border);

Unfortunately, it can't. The exact value displayed in the pop-up dialog box is inconsistent between different browsers.

l Explorer 6 gives #cc0000 1px solid.

l Mozilla 1.7.12 gives 1px solid rgb(204,0,0).

l Opera 9 gives 1px solid #cc0000.

l Safari 1.3 does not give any border value.

The problem is that border is a shorthand declaration. It implicitly includes no less than 12 styles: width, style and color of the top, left, bottom and right borders. Similarly, the font declaration is shorthand for font-size, font-family, font-weight, and line-height, so it will exhibit similar problems.

rgb()

Note the special color syntax used by Mozilla: rgb(204,0,0). This is a valid alternative to the traditional #cc0000. You can choose any syntax between CSS and JavaScript.

How do browsers handle these abbreviated declarations? The above example seems too direct; your intuition should be to expect the browser to return 1px solid #cc0000, ensuring that it is consistent with what is defined by the inline style. Unfortunately, shorthand properties are more complicated than that.

Consider the following situation:

p {

border: 1px solid #cc0000;

}

Test



alert(document.getElementById('test').style.borderRightColor);

All browsers report the correct color, although border-right- is not included in the inline style color declares border-color instead. Apparently the browser thinks that the color of the right border is set when the entire border color is set, which is also logical.

As you can see, browsers have to make rules for these exceptions, and they have chosen to handle shorthand declarations in slightly different ways. In the absence of a clear specification for handling abbreviated attributes, it is difficult to judge which browser is right or wrong.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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.

How to modify element.style How to modify element.style Nov 24, 2023 am 11:15 AM

Methods for element.style to modify elements: 1. Modify the background color of the element; 2. Modify the font size of the element; 3. Modify the border style of the element; 4. Modify the font style of the element; 5. Modify the horizontal alignment of the element. Detailed introduction: 1. Modify the background color of the element, the syntax is "document.getElementById("myElement").style.backgroundColor = "red";"; 2. Modify the font size of the element, etc.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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).

See all articles