Javascript Manipulating CSS Learning notes

Source: Internet
Author: User

The page tends to be dynamic, we often need to manipulate the style of the elements in the script, when we just learned JS, we all know that CSS style related properties are set by the style property, but sometimes we want to get the style first, the result is that the value obtained by the style is empty. This requires that we are skilled enough in these concepts.

First, set the style

Each DOM element has a style property, and unlike usual properties, the value of the style is a Cssstyledeclaration object that represents the inline style of the corresponding element.
Note that the inline style is mentioned above, and we know that the <link> style referenced inside is called an external style, the style that is <style> written inside the tag is called the outer style, and the inline style is called in the element tag by assigning a value directly within the Style property.
While in most cases we are using an external style, the inline style has precedence over the external style, and we assign a value to the style property of the element, rather than having an inline style assigned to it, overwriting the original style of the same property. This is why sometimes you can't get a value by using the Style property: Because you don't specify an inline style for an element.

<style> #box{  width: px;         Height: + px; / * Set the color value in the inline style * /         color: #fff;     background-color: #ff9000; }            </style>
<!--在内联样式中设置position--><div id="box" style="position: relative">盒子</div>
var box = document. getElementById("box");Console. Log(Box. Style. Color); Null because no Color property is set within inline styleConsole. Log(Box. Style. Position); Output "relative" because the position is set in the inline styleBox. Style. Color="#000"; Successfully set color valueConsole. Log(Box. Style. Color); Output "RGB (0, 0, 0)", as has just been set
Naming conventions

Because the hyphen in JS is the minus sign, so in CSS similar to font-size: 20px this with the hyphen character property is not directly accessible through style.font-size, should be removed, and the hyphen after the first letter uppercase, or through the form of array access to assign values, such as:

box.style.fontSize"20px";//或 box.style["font-size""20px"

In addition, for properties such as float, which are reserved characters in JS, it is best to add a CSS prefix to it to make it a legitimate property, such as

box.style.cssFloat"left";
Attention

The value of all properties of a style should be a string, and all positional properties need to contain units when positioning the property using the style setting.

box.style.left300;    //无效,300不是字符串box.style.left"300";     //无效,没有带单位box.style.left"300px";   //这就对了

In summary, it is convenient to use a style for styling, but it is very difficult to read the style, first the returned values are in units, and secondly for a composite property like margin because it gets a string, it also needs to be split into four direction values.

Finally, by setattribute and setting the Csstext value of the style, you can also write all the styles at once, assigning them to the elements at once:

"float: left; margin: 0 10px;"box.setAttribute("style", s);//或者box.style.cssText = s;//读取也是一样的s = box.getAttribute("style");//或者s = box.style.cssText;
Get calculation style

In general, we don't really care whether it's inline or out-of-the-style, just want to get the style value of the element, and the actual value of the property used when the element is finally displayed becomes the calculation style.
The calculated style is also a Cssstyledeclaration object, called through the Window object. (Not supported under IE8)

varwindow":before");

As you can see, the first parameter represents the element that needs to get the style, the second parameter represents the pseudo-object's string, and can be set to null or an empty string if it is not required.

Also use properties for access:

varwindow"");console.log(styles.marginLeft);         //输出"0px",虽然并没有显示指定过marginLeft
Difference

Although the Cssstyledeclaration objects are obtained through style and getComputedStyle, they are somewhat different.

    1. The properties of the latter (the Cssstyledeclaration object obtained through getComputedStyle) are read-only.
    2. The value of the latter is absolute, that is, you can set the percentage of "50%", to the last obtained is a specific value, the size is expressed as px suffix string, the color is expressed as "RGB (#, #, #)" or "Rgba (#, #, #, #)".
    3. No composite attributes, such as margin, will return an empty string (depending on the browser, Chrome supports return). It is best to use specific attributes such as marginleft.
    4. Without the Csstext property, an empty string will be returned (depending on the browser, Chrome supports return).
    5. For positional properties, if not absolutely positioned, access left, top, and other positional properties return "Auto"

So we can use both to read the style and to set the style. Such as

var box = document.getElementById("box");var"");//将文本尺寸放大两倍varparseInt2"px";

For IE, it has its own Cssstyledeclaration object, obtained through Currentstyle.

Third, set the class name

Long ago, the class name that gets an element is obtained through the ClassName property, and for an element with only a single class name, once the element has multiple class names, the resulting string of multiple class names separated by spaces needs to be decomposed on its own.

<divid="box"class="red btn whatever">盒子</div>
vardocument.getElementById("box");console//"red btn whatever"

In HTML5, the element has a new classlist attribute, which is a read-only object, but provides a convenient way to manipulate the class name:

    • Add (ClassName) class name
    • Remove (ClassName) removes the class name
    • Toggle (ClassName) If no such name is present, add, or delete the class name if it exists
    • Contains (ClassName) detects whether the specified class name is included

With these methods is more convenient (for unsupported browsers, of course, you can actually implement these methods yourself)

var classlist = Box. Classlist;Classlist. Add("AAA");Console. Log(Box. ClassName); "Red btn whatever AAA"Classlist. Remove("Red");Console. Log(Box. ClassName); "Btn whatever AAA"Classlist. Toggle("BBB");Console. Log(Box. ClassName); "Btn whatever AAA BBB"Classlist. Contains("AAA"); True

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Javascript Manipulating CSS Learning notes

Related Article

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.