PPK on the _javascript techniques of JavaScript style attributes

Source: Internet
Author: User
In fact, 7 sample scripts use some form of CSS modification. For example, form validation changes the style of an error form field, and the XMLHTTP speed Tester uses animations (that is, changing a style several times in a short time) to get the user to notice the speed data (and, frankly, it's a bit of a fancy effect). The Drop-down menu displays and hides the menu items by changing the style. These changes have the same purpose: to draw the attention of the user 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 class or ID (element.classname= ' error ') of the element, and the browser will automatically apply those styles defined on the new class or ID;

L write new CSS directives to the document (document.write (' <style>.accessibility{display:none}</style> ');

L Change the style sheet for the entire page.

Most CSS change scripts take the form of modifying the style property or changing the class or ID. The Document.Write method is only suitable for certain occasions to enhance the accessibility of the page. In the end, we rarely change the entire stylesheet, because not all browsers support it, and often you just want to change the style of some particular element.

Anyway, I've used all 4 methods in the sample script. We will look at these methods and their applications in this chapter one by one.

A Style Property

The first and most well-known way to modify CSS is through the style attributes owned by all HTML elements and accessing their inline styles, which contain a corresponding attribute for each inline CSS declaration. If you want to set an element of CSS properties margin, use Element.style.margin. If you want to set its CSS property color, use Element.style.color. JavaScript attributes always have a name similar to CSS properties.

inline style

Remember that the style property of the HTML element gives us access to the inline style of the element.

Let's review some of the CSS theories. CSS provides 4 ways to define a style sheet for an element. You can use inline styles, which directly write your CSS in the style attribute of the HTML tag.

<p style= "margin:10%" >Text</p>

In addition, you can embed, link, or introduce a style sheet. In any way, because inline styles are more specific than any other form of style, inline styles can override those defined in a style sheet that is embedded, linked, or introduced into a page. Because the Style property can access these inline styles, it can always overwrite other styles. This is the great advantage of this approach.

However, when you try to read a style, you may encounter problems. Look at this example:

<p id= "Test" >Text</p>

p#test {

margin:10%;

}

Alert (document.getElementById (' Test '). Style.margin);

The test paragraph does not contain any inline styles, and margin:10% is defined in an embedded (or chained, or introduced) style sheet that cannot be read from the style attribute. The pop-up warning box appears empty.

In the next example, the pop-up warning box will display the return result "10%" because margin is now defined as an inline style:

<p style= "margin:10%" id= "test" >Text</p>

Alert (document.getElementById (' Test '). Style.margin);

Therefore, the Style property is best suited for styling and is less useful for getting them. Later we'll discuss ways to get styles from embedded, chained, or introduced style sheets.

Dash

Many CSS properties have names that contain a dash, such as font-size. In JavaScript, however, a dash represents a subtraction (minus), so it cannot be used in a property name. This will give you an error:

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

Does this require the browser to subtract (undefined) the variable size from the Element.style.font? If yes = ' 120% ' What does it mean? Instead, the browser expects an attribute name for the hump format (CamelCase):

element.style.fontSize = ' 120% ';

The general rule is to remove all dashes from the CSS property name, and the characters after the dash become uppercase. In this way, margin-left into a marginleft,text-decoration into a textdecoration, and Border-left-style into a borderleftstyle.

Unit

In JavaScript, the values for many numeric types require a unit, as they are declared in CSS. What does fontsize=120 mean? 120 pixels, 120 pounds or 120%? Browsers don't know about this, so it won't do any reaction. In order to clarify your intentions, the unit is necessary.

Taking the SetWidth () function as an example, it is one of the core programs to realize the animation effect of "XMLHTTP speedometer":

[XMLHTTP speedometer, line 70th to 73rd]

function SetWidth (width) {

if (Width < 0) width = 0;

document.getElementById (' meter '). Style.width = width + ' px ';

}

The function takes over a value that will change the width of the meter to this new value. After a security check is made to ensure that the value is greater than 0, the style.width of the element is set to the new width value. Finally add ' px ', because otherwise, the browser may not know how to interpret the value, the result is nothing.

Don't forget the ' px '

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

In CSS quirks mode (quirks mode), adding ' px ' is not necessary because the browser follows the old rules and treats the value of no units as pixel values. In essence this is not a problem, but many web developers have developed the habit of forgetting to add units after changing width or height values, and they are encountering problems when they work under CSS Strict mode (strict mode).

Get style

Warn that there are browser compatibility issues with the content described below.

As we can see, the Style property cannot read styles that are set in a style sheet that is embedded, linked, or introduced into a page. But because web developers sometimes need to read these styles, both Microsoft and the consortium provide a way to access non inline styles. Microsoft's solution can only work under the Explorer, while the standard of the consortium can work under Mozilla and opera.

Microsoft's solution is the Currentstyle attribute, which works like a style attribute, except for two things:

L It can access all styles, not just inline styles, so it reports on the actual style applied to the elements;

L It's read-only and you can't set the style through it.

For example:

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

alert (X.currentstyle.color);

Now the pop-up dialog box displays the current color style of the element, regardless of where it is defined.

The solution for the consortium is the window.getComputedStyle () method, which works in a similar but syntactically more complex way:

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 incompatible situations, we need some code branches 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 that getComputedStyle () will always return a pixel value, while Currentstyle retains the units originally defined in the CSS.

Shorthand style

Warn that there are browser compatibility issues with the content described below.

Whether you get inline styles through the style attribute or get other styles from the function you just discussed, you'll have problems when you try to read the shorthand style.

Look at the definition of this border (border)

<p id= "test" style= "border:1px solid #cc0000;" >Text</p>

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

Alert (document.getElementById (' Test '). Style.border);

Unfortunately, it can't. The exact values displayed by different browsers in the pop-up dialog box are inconsistent.

L Explorer 6 gives the #cc0000 1px solid.

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

L Opera 9 gives the 1px solid #cc0000.

L Safari 1.3 does not give any border values.

The problem is that the border is a shorthand statement. It includes not less than 12 styles: the width, style, and color (color) of the top, left, bottom (bottom) and right borders. Similarly, the font declaration is shorthand for font-size, font-family, Font-weight, and line-height, so it also exhibits similar problems.

RGB ()

Note the special color syntax used by Mozilla: rgb (204,0,0). This is a valid substitution value for the traditional #cc0000. You can use any of the syntax in CSS and JavaScript.

What does a browser do with these shorthand statements? The example above seems too straightforward; your intuition should be to expect the browser to return 1px solid #cc0000 to ensure consistency with the inline style definition. Unfortunately, the shorthand attribute is much more complex than that.

Consider the following scenario:

p {

border:1px solid #cc0000;

}

<p id= "test" style= "Border-color: #00cc00;" >Test</p>

Alert (document.getElementById (' Test '). Style.borderrightcolor);

All browsers report the correct color, although the inline style does not contain border-right-color but declares Border-color. It is also logical that the browser thinks the color of the right border is set when you set the entire color of the borders.

As you can see, browsers must make rules for these anomalies, and they have opted for a slightly different way of dealing with shorthand statements. In the absence of a clear specification for handling shorthand attributes, it is difficult to judge which browser is right or wrong.

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.