PPK about JavaScript style attributes

Source: Internet
Author: User

In fact, all seven sample scripts use some form of CSS modification. For example, "Form Verification" changes the style of the wrong form field, and "XMLHTTP speed tester" uses an animation (in fact, a style is changed multiple times in a short time) to let users notice the speed data (and, to be honest, this is somewhat fancy ). The "drop-down menu" shows and hides menu items by changing the style. These changes share the same purpose: to attract users' attention to these elements.

Javascript has the following four methods to modify CSS:

L modify the style attribute of an element (element. style. Margin = '2013 ');

L change the class or ID of an element (element. classname = 'error'). The browser automatically applies the styles defined on the new class or ID;

L write new CSS commands to the document (document. Write ('<style>. Accessibility {display: None} </style> ');

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. The document. Write method is only applicable to certain scenarios to enhance page accessibility. Finally, we rarely change the whole style sheet, because not all browsers support this, And you usually just want to change the style of some specific elements.

In any case, I use all four methods in the sample script. We will study these methods one by one and their applicability in this chapter.

A style attribute

The most widely known way to modify CSS is to access their inline styles through style attributes owned by all HTML elements, the style object contains a corresponding attribute for each inline CSS declaration. If you want to set the CSS attribute margin of an element, use element. style. margin. If you want to set the CSS attribute color, use element. style. color. The JavaScript property always has a name similar to the CSS property.

Inline Style

Remember: The style attribute of an HTML element allows us to access the inline style of the element.

Let's review some CSS theories. CSS provides four methods to define style sheets for elements. You can use inline styles to 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. No matter what method is used, because inline styles are more explicit than any other form of styles, inline styles can overwrite the styles defined in the style sheets embedded, chained in, or introduced to pages. Because the style attribute can access these inline styles, it can always overwrite other styles. This is a huge advantage of this method.

However, you may encounter problems when trying to read styles. Let's look at this example:

<P id = "test"> text </P>

P # test {

Margin: 10%;

}

Alert (document. getelementbyid ('test'). style. margin );

The test section does not contain any inline styles. Margin: 10% is defined in an embedded (or chained, or introduced) style sheet, it cannot be read from the style attribute. The pop-up warning box is blank.

In the next example, the pop-up warning box will show the returned 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 attribute is most suitable for setting styles, but it is not so useful to obtain them. Later, we will discuss how to obtain styles from embedded pages, chained or introduced style sheets.

Break number

The names of many CSS attributes contain a broken number, such as font-size. However, in Javascript, a broken number represents a subtraction (minus), so it cannot be used in attribute names. This will give an error:

Element. style. Font-size = '000000 ';

Does this require the browser to subtract the (undefined) variable size from element. style. font? What does = '20160301' mean? As an alternative, the browser expects a camelcase attribute name:

Element. style. fontsize = '000000 ';

The general rule is to remove all the creden from the CSS attribute name and change the characters after the creden。 to uppercase. In this way, margin-left is changed to marginleft, text-decoration is changed to textdecoration, and border-left-style is changed to borderleftstyle.

Unit

Many numeric values in Javascript require a unit, just as they are declared in CSS. What does fontsize = 120 mean? 120 pixels, 120 lbs, or 120%? The browser does not know this, so it will not respond. Units are required to clarify your intentions.

Taking the setwidth () function as an example, it is the core of the "XMLHTTP speedometer" animation effect.ProgramOne:

[XMLHTTP speedometer, 70th ~ 73 rows]

Function setwidth (width ){

If (width <0) width = 0;

Document. getelementbyid ('meter '). style. width = width + 'px ';

}

This function takes over a value and changes the meter width to this new value. After a security check to ensure that the value is greater than 0, set the style. Width of the element to the new width value. In this case, the browser may not know how to interpret the value, and the result will not do anything.

Don't forget 'px'

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

In the quirks mode of CSS, adding 'px 'is not necessary, because the browser follows the old rules and regards the ununit value as the pixel value. This is not a problem in nature, but many web developers have developed the habit of forgetting to add units after changing the width or height value. When they work in strict mode (strict mode) and then encountered a problem.

Get Style

Warning the following content has browser compatibility issues.

As we can see, the style attribute cannot read styles set in the style sheet embedded, chained in, or introduced into the page. However, because Web developers sometimes need to read these styles, both Microsoft and W3C provide a way to access non-inline styles. Microsoft's solutions can only work under explorer, while W3C standards can work under Mozilla and opera.

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

L it can access all styles, not just inline styles, so it reports styles actually applied to elements;

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

For example:

VaR x = Document. getelementbyid ('test ');

Alert (X. currentstyle. Color );

The pop-up dialog box displays the current color style of the element, no matter where it is defined.

The W3C solution is the window. getcomputedstyle () method, which works in a similar but 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 incompatibility, we need someCodeBranch to meet 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 the following function:

VaR textdecstyle = getrealstyle ('test', 'textrecoration ');

Remember that getcomputedstyle () always returns a pixel value, while currentstyle retains the unit originally defined in CSS.

Simplified Style

Warning the following content has browser compatibility issues.

Whether you use the style attribute to obtain inline styles or use the function you just discussed to obtain other styles, you will encounter problems when you try to read short styles.

See 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 cannot. The exact values displayed by different browsers in the pop-up dialog box are inconsistent.

L Explorer 6 provides # cc0000 1px solid.

L Mozilla 1.7.12 provides 1px solid RGB (204,0, 0 ).

L opera 9 provides 1px solid # cc0000.

L safari 1.3 does not provide any border value.

The problem is that border is a short statement. It secretly includes no less than 12 styles: Top, left, bottom, width, and style of the right border) and color ). Similarly, the font statement is a short form of font-size, font-family, font-weight, and line-height, so it also shows similar problems.

RGB ()

Note the special color syntax used by Mozilla: RGB (204,0, 0 ). This is a valid replacement value for the traditional # cc0000. You can select a syntax in CSS or JavaScript.

How does the browser handle these abbreviated statements? The above example seems too straightforward; your intuition should be that the browser should return 1px solid # cc0000 to ensure that it is consistent with the inline style defined. Unfortunately, attributes in short form are much more complex than those in other forms.

Consider the following situation:

P {

Border: 1px solid # cc0000;

}

<P id = "test" style = "border-color: #00cc00;"> test </P>

Alert (document. getelementbyid ('test'). style. borderrightcolor );

All browsers report correct colors, although the inline style does not contain border-right-color but declares border-color. Obviously, the browser determines that the right border color is set when the entire border color is set, which is also logical.

As you can see, the browser must set rules for these exceptions, and they have chosen a slightly different way to handle short-form declarations. In the absence of clear rules for handling abbreviated attributes, it is difficult to judge which browser is right or wrong.

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.