CSS learning notes for Javascript operations, javascriptcss

Source: Internet
Author: User

CSS learning notes for Javascript operations, javascriptcss

Pages often change dynamically. We often need to operate on element styles in scripts. When I first learned about js, we all know that css style-related attributes are set through style attributes, but sometimes we also want to get the style first, and the result shows that the value obtained through the style is null, which requires us to be skilled in these concepts.

1. Set styles

Each dom element has a style attribute. Unlike common attributes, the style value is a CSSStyleDeclaration object. The attribute of this object representsInline style of the corresponding element.
Note that the above is an inline style. We know that<link>The referenced style is called an external style.<style>A style written in a tag is called an external style, while an inline style is directly assigned a value through the style attribute in an element tag.
Although we use external styles in most cases, inline styles have a higher priority than external styles under the same conditions. We assign a value to the style attribute of an element, it is equivalent to specifying an inline style for it, so it overwrites the style of the original same attribute. This is also the reason why sometimes the value cannot be obtained through the style attribute: because you have not specified an inline style for the element.

<Style> # box {width: 100px; height: 100px;/* set the color value in the external style */color: # fff; background-color: # ff9000 ;} </style>
<! -- Set position in the inline style --> <div id = "box" style = "position: relative"> box </div>
Var box = document. getElementById ("box"); console. log (box. style. color); // null, because the color Attribute console is not set in the inline style. log (box. style. position); // output "relative" because positionbox is set in the inline style. style. color = "#000"; // The color value is successfully set to console. log (box. style. color); // output "rgb (0, 0, 0)", because you have set
Naming Conventions

Because the hyphen in js is a minus sign, it is similarfont-size: 20pxThis type of property with a hyphen cannot be directly passed through style. for font-size access, you should remove the hyphen and upper the first letter after the hyphen, or assign values through array access, such:

Box. style. fontSize = "20px"; // or box. style ["font-size"] = "20px"

In addition, for attributes that retain characters in js such as float, it is best to add a css prefix to it to make it a legal attribute, such

box.style.cssFloat = "left";
Note:

The value of all attributes of the style should be a string. When you use the style to set the positioning attribute, all positioning attributes must contain units.

Box. style. left = 300; // invalid. 300 is not a string box. style. left = "300"; // invalid, with no unit box. style. left = "300px"; // This is correct.

In summary, it is convenient to set styles, but it is very difficult to read styles. First, the returned values are all in units, secondly, for a composite attribute like margin, because the string is obtained, you also need to split it into four values.

Finally, you can use setAttribute and cssText to set the style values. You can also write all styles at one time and assign values to the elements at one time:

Var s = "float: left; margin: 0 10px;" box. setAttribute ("style", s); // box.style.css Text = s; // read the same s = box. getAttribute ("style"); // or s = box.style.css Text;
Get computing style

In general, we don't really care about whether it is an inline style or an external style. We just want to get the style value of the element. When the element is finally displayed, the actual attribute value becomes a calculated style.
The calculation style is also a CSSStyleDeclaration object called through the window object. (Not supported by IE8 or earlier)

var styles = window.getComputedStyle(element, ":before");

As you can see, the first parameter represents the element that needs to get the style, and the second parameter represents the string of the pseudo object. You can set it to null or null if you do not need it.

Similarly, access using properties:

Var styles = window. getComputedStyle (box, ""); console. log (styles. marginLeft); // output "0px", although the specified marginLeft is not displayed
Differences

Although CSS styledeclaration objects are obtained through style and getComputedStyle, there are some differences between them.

Therefore, you can use the two methods to read and set styles. For example

Var box = document. getElementById ("box"); var styles = window. getComputedStyle (box, ""); // enlarge the text size by twice var size = parseInt (styles. fontSize); box. style. fontSize = size * 2 + "px ";

IE has its own CSSStyleDeclaration object, which is obtained through currentStyle.

3. Set the class name

A long time ago, the class names of an element were obtained through the className attribute. For elements with only one class name, once an element has multiple class names, the result is a string separated by multiple class names by space characters, which must be decomposed by yourself.

<Div id = "box" class = "red btn whatever"> box </div>
var box = document.getElementById("box");console.log(box.className); //"red btn whatever"

In HTML5, the element adds a classList attribute, which is a read-only object, but provides a convenient method for operating class names:

  • Add (className) add class name
  • Remove (className) remove Class Name
  • Toggle (className) If this class name does not exist, add it. If yes, delete this class name.
  • Contains (className) checks whether it contains the specified class name

With these methods, it is much more convenient (for browsers that are not supported, you can also implement these methods on your own)

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 Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.