JavaScript HTML DOM - changing CSS

JavaScript HTML DOM - Change CSS

There are 4 ways to modify CSS in JavaScript:

Modify node style (inline style);

Change the node class or id;

Write new css;

Replace the style sheet in the page.

Personally, I 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. The usage 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., and they are all connected with dashes (-) , however in JavaScript the dash means "minus", so it 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 immediate styles (related to behavior) of elements that change frequently. For example, a div that can be used for dragging will change its The top and left attributes are constantly changing. At this time, they cannot be defined by class or other methods. Using this method, the style can be modified immediately and override other settings.

2. Change class, 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 JavaScript Hooks may cause unnecessary errors.

In JavaScript, class is a reserved keyword, so use className as the attribute to access the element's 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 property that contains all classes of the element. string, all classes are separated by spaces, which makes it inconvenient to delete classes (just add, 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 it in className Add a space at the beginning and end of the attribute, then everything becomes the middle method, directly replace the substring:

//Delete 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. Obtaining the real style

The first thing to make clear is , it is not possible to pass element.style. It can only obtain inline styles, and the definition 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 it before using it:

//获取元素样式
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 that some form options are added dynamically. For example, in one of your forms, you select the marriage status of "Married" , then there will be an additional input box for you to enter your spouse's name.

If there is no choice, then of course the "spouse" related forms must be hidden, but at this time, CSS should not be used to solve the problem, that is, style.display="none" cannot be used to hide it.

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

The correct way is to put this content into the DOM hyperspace, so that it will not I have the above problem


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <h1 id="id1">我的标题 1</h1> <button type="button" onclick="document.getElementById('id1').style.color='red'"> 点我!</button> </body> </html>
submitReset Code