English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Simple Method to Set CSS Styles with cssText in JavaScript

If there is a tag with an id of "no" in the web page, let's temporarily treat it as a div tag to tell;

To set the CSS style of this div in JavaScript, a very common practice is:

var obj = document.getElementByIdx_x_x('no');
obj.style.width = '"400px';
obj.style.height = '"300px';

If you need to set a lot of CSS styles, it's too麻烦了、

Generally, it will be combined with css to add className or change className to achieve the desired effect, but if you create an element, do you want it to be this simple? Then you need to think of another way~

So everyone wrote one function after another, the classic ones are:

var obj = document.getElementByIdx_x_x('no');
function setStyle(obj, css) {
for(var attr in obj){
obj.style[attr] = css[attr];
}
}
setStyle(obj,{width:"400px",height:"300px"});

Of course, there is an even simpler way, cssText:

var obj = document.getElementByIdx_x_x('no');
obj.style.cssText = "width:400px; height:300px;

Of course, this method is very simple and convenient for initializing CSS styles for elements created by create.

This is the full content of the simple method of setting CSS styles with cssText in JavaScript that the editor has brought to you. Hope it helps everyone, and please support the呐喊 tutorial~

You May Also Like