Home  >  Article  >  Web Front-end  >  Summary of methods for changing CSS styles in JavaScript_javascript skills

Summary of methods for changing CSS styles in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:00:281249browse

JavaScript allows you to change CSS styles on the fly, so that you can draw the user's attention to where you want them to focus, and provide a better interactive experience.

There are 4 ways to modify CSS using JavaScript:

Modify node style (inline style);
Change node class or id;
Write new css;
Replace the stylesheet in the page.

I personally do not recommend using the latter two methods. Almost all functions can be achieved through the first two methods, and the code is clearer and easier to understand.

I will also talk about how to get the real style of the element and the precautions in a form later.

1. Modify node style (inline style)

This method has the highest weight. It is written directly on the style attribute of the node. It will override the style set by other methods. How to use is very simple:

var element = document.getElementById("test");
element.style.display = "none" //让元素隐藏

But it should be noted that some CSS style names are composed of several words, such as font-size, background-image, etc. They are all connected with dashes (-). However, in JavaScript, dashes mean "minus" , and therefore cannot be used as an attribute name. We need to use "camelCase" to write attribute names, such as fontSize, backgroundImage.

Also note that many styles have units and cannot be given just a number. For example, the units of fontSize include px, em, % (percentage), etc.

This method violates the principle of separation of performance and behavior. It is generally only suitable for defining real-time styles (related to behavior) of elements that change frequently. For example, a div that can be used for dragging will change its top and left as it is dragged. Attributes are constantly changing. At this time, they cannot be defined by class or other methods. Using this method, the style can be modified on the fly and override other settings.

2. Change class and id

id and class are "hooks" for setting styles. After changes, the browser will automatically update the style of the element.

The method of changing id is similar to that of class, but I personally do not recommend using it this way because id is used to locate elements. It is best not to use it to define the display style of elements, and id is often used as a JavaScript hook. May cause unnecessary errors.
In JavaScript, class is a reserved keyword, so use className as the attribute to access the element class, for example:

.redColor{
 color: red;
}
.yellowBack{
 background: yellow;
}
element.className = "redColor";//设置class
element.className += " yellowBack";//增加class

But what is more depressing is that this attribute is a string containing all classes of the element. All classes are separated by spaces, which makes it very inconvenient when deleting classes (just add them, just make a string connection between them) , but remember to add a space in front~).

I used regular expressions when deleting, and deleted the class according to its different positions in the string (head, tail, middle), but then I thought of a better way, which is to delete the class at the beginning and end of the className attribute. Add a space to each, and then everything becomes the middle method, directly replacing the substring:

//删除class
function 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. Define the CSS style. JavaScript only issues instructions for style changes. The specific style definition is still left to CSS.

The last two methods are neither elegant nor have certain compatibility issues, so I won’t introduce them~

3. Get the real style

The first thing to make clear is that it is not possible to use element.style. It can only obtain inline styles, and the definitions in the style sheet cannot be obtained.
Since the style of an element can be defined in so many places, it is hard to say what its real style looks like. Is there any way to get the real 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:

//获取元素样式
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 styleName passed in is in "camel case format"~~

4. Displaying and hiding forms (do not abuse CSS)

We often see some form options added dynamically. For example, if you select "Married" as your marital status in a form, then there will be an additional input box for you to enter your spouse's name.

If there is no choice, then of course you have to hide all the "spouse" related forms, but you should not use CSS to solve it at this time, that is, you cannot use style.display="none" to hide it.

Because no matter you hide it or not, the input box is there, neither increasing nor decreasing~ [Halo] To put it bluntly, although it is hidden, it still exists in the DOM. If the user submits the form at this time , the content of this hidden input box will be submitted together, and some unexpected errors may occur~

The correct approach is to put this content into the DOM hyperspace, so that there will be no above problems.

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

Statement:
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