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.