JavaScript method for changing CSS styles _ javascript skills

Source: Internet
Author: User
There are four methods to modify CSS in JavaScript: 1. modify node style (inline style); 2. change the class or id of a node. 3. write new css; 4. replace the style sheet on the page. Today, I will introduce the first two types of content, because the last two types of content are not very recommended for you to use JavaScript to allow you to change the CSS style in real time, in this way, the user's attention can be attracted to the places you want them to focus on, and a good interactive experience can be provided.

There are four methods to modify CSS in JavaScript:

Modify node style (inline style );
Change the class or id of a node;
Write new css;
Replace the style sheet on the page.

I personally do not recommend using the last two methods. almost all functions can be implemented in the first two methods, and the code is clearer and easier to understand.

We will also talk about how to get the true style of an element and the precautions in a form.

1. modify the node style (inline style)

This method has the highest weight and is directly written on the style attribute of the node. it overwrites the style set by other methods. The usage is simple:

Var element = document. getElementById ("test"); element. style. display = "none" // hide the element

However, it should be noted that some CSS style names are composed of several words, such as font-size and background-image. they are all connected by a break, however, a broken number in JavaScript indicates "subtraction", so it cannot be used as an attribute name. We need to use camelCase to write attribute names, such as fontSize and backgroundImage.

Note that many styles are in units and cannot be given only one number. For example, the unit of fontSize is px, em, % (percentage), etc.

This method violates the principle of separation of performance and behavior. generally, it is only suitable for defining instant styles that frequently change elements (related to behavior). For example, a p can be used for drag and drop, its top and left attributes are constantly changing. at this time, they cannot be defined using class or other methods. this method can be used to instantly modify the style and overwrite other settings.

2. change the class and id

Id and class are the "hooks" for setting styles. after the changes, the browser automatically updates the styles of the elements.

The method to change the id is similar to that of the class, but it is not recommended for individuals. because id is used to locate the element, it is best not to use it to define the display style of the element, and the id is often used as a JavaScript hook, which may cause unnecessary errors.
In JavaScript, class is a reserved keyword, so className is used as an attribute to access the element class. for example:

. RedColor {color: red;}. yellowBack {background: yellow;} element. className = "redColor"; // Set classelement. className + = "yellowBack"; // add a class

However, it is depressing that this attribute is a string containing all the classes of the element. all classes are separated by spaces, which makes it inconvenient to delete the class, make a string connection between them, but remember to add a space before it ~).

I used a regular expression to delete the class at different positions in the string (header, tail, and center). However, I came up with a better solution, add a space at the beginning and end of the className attribute, and then all become the middle method. replace the substring directly:

// Delete classfunction removeClass (element, classRomove) {var classNames = "" + element. className + ""; classNames = classNames. replace ("" + classRomove + "", ""); // String. trim (classNames); element. className = classNames ;}

It is best to use this method for general style modifications to define the CSS style. JavaScript only sends the style change instruction. the specific style definition should be handed over to CSS.

The last two methods are neither elegant nor compatible. I will not introduce them ~

3. get real styles

First of all, it should be clear that element. style cannot be used, and only inline styles can be obtained, and definitions in style sheets cannot be obtained.
Since the style of an element can be defined in so many places, it is hard to say what the actual style looks like, is there any way to get the true style of the element displayed in the browser?
In fact, both Microsoft and W3C provide corresponding methods. we only need to encapsulate them to use them:

// Obtain the element style function getRealStyle (element, styleName) {var realStyle = null; if (element. currentStyle) {realStyle = element. currentStyle [styleName]; // IE} else if (window. getComputedStyle) {realStyle = window. getComputedStyle (element, null) [styleName]; // W3C} return realStyle ;}

Remember that the imported styleName is in the "camper format ~~

4. display and hide forms (do not abuse CSS)

We often see that some form options are dynamically added. for example, if you select "married" in a form, you will have an additional input box asking you to enter the name of your spouse.

If no choice is made, the related forms of "spouse" should be hidden, but CSS should not be used at this time, that is, style cannot be used. display = "none" to hide.

Because no matter whether you hide it or not, the input box is there, without increasing or decreasing it ~ [Dizzy] to put it bluntly, although it is hidden, it still exists in the DOM. if the user submits a form at this time, the content of this hidden input box will be submitted together, unexpected errors may occur ~

The correct method is to put the content in the DOM hyperspace, so that there will be no above problems.

The above is all the content of this article. I hope you will like it.

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.