Home > Web Front-end > JS Tutorial > body text

Summary of styles methods for modifying css attributes such as style, id, class, etc. in JavaScript

伊谢尔伦
Release: 2018-05-15 15:08:16
Original
18639 people have browsed it

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 in JavaScript:

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

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 other methods. The style set. The usage is very simple:

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

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 real-time styles (related to behavior) of elements that change frequently. For example, a p that can be used for dragging. As it is dragged, 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 the "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 also used. Often used as a JavaScript hook, it 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
Copy after login

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 is very inconvenient when deleting classes (just add, just make a string connection between them, but remember to add a space before it~).

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 the className Add a space at the beginning and end of the attribute, then it will all become the middle method, directly replace the substring:

//删除class
function removeClass(element,classRomove){
var classNames = " "+element.className+" ";
classNames = classNames .replace(" "+classRomove+" ", " ");
//String.trim(classNames);
element.className = classNames;
}
Copy after login

It is best to use this method for general style modification, and define the CSS style. JavaScript only issues instructions for style changes, and the specific style definition is left to CSS.

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

3. Obtain 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 before using 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;
}
Copy after login

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 the marital status in a form, "Married", then there will be an additional input box for you to enter your spouse's name.

If there is no choice, of course you have to hide all the related forms of "spouse", but at this time you should not use CSS to solve it, that is, you cannot use style.display="none" 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 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 there won’t be the above problem.

The above is the detailed content of Summary of styles methods for modifying css attributes such as style, id, class, etc. in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!