Home Web Front-end HTML Tutorial HTML、CSS及JavaScript : JavaScript征服Style的五种武器_html/css_WEB-ITnose

HTML、CSS及JavaScript : JavaScript征服Style的五种武器_html/css_WEB-ITnose

Jun 24, 2016 am 11:15 AM

在HTML的世界里,对于一个元素来说,看的主要不是气质,而是它的Style,因为Style决定了颜值。俗话说,JavaScript与Style,得其一者得天下。但是,Style永远无法改变JavaScript,JavaScript却可以征服Style。因为JavaScript有五种武器,所以可以对Style为所欲为,既可远观,亦可亵玩。

第一种武器是 className,在JavaScript,得到一个元素的 className就是得到了这个元素的 class属性的值。Show Code:

<div id="box" class="one two"/><script>  var box = document.getElementById("box")  alert(box.className)  box.className += ' three'</script>
Copy after login

上面的代码拿到 box的 class,然后又给它添加了一个 three。如果想去掉某个 class,只要通过字符串操作去掉,然后重新给 className赋值就可以了。

第二种武器是 style,确切地说,这是个武器包,你几乎可以用它修改所有 style。比如说你执行了 box.style.width='100px',就相当于在 box上添加了一个 style="width:100px"。

对于那些由多个单词组成的style值,就是 background-color、 marigin-top之类的,要把横线去掉,然后单词的首字母大写。对,改成像 backgroundColor、 mariginTop这样。像 -moz-border-radius这种,也是把 -去掉,然后后面的字母换成大写,就是改成 MozBorderRadius。

因为style属性优先与css,所以你可以用style覆盖掉css中设置的样式,也可以把它设成空字符串还原:

var box = document.getElementById("box")box.style.width='100px'box.style.width=''
Copy after login

上面的代码最终会保持box的 width不变。

第三种武器是 cssText,好吧,实际上它也是style中的一个属性。但因为它很强大,所以我们特意提高了它的地位。用 style.cssText可以获取和设置完整的style内容。

<div>Button</div><script>  var div = document.body.children[0]  div.style.cssText='color: red !important; \    background-color: yellow; \    width: 100px; \    text-align: center; \    blabla: 5; \  '  alert(div.style.cssText)</script>
Copy after login

浏览器会对 cssText进行解析,然后把解析结果应用到元素上去。上面代码中那个不认识blabla就直接忽略掉了,不会报错,所以要注意typo。

并且如果你想加 !important,只能用 cssText。

接下来要出场的,是真正重量级的两种武器,或者说一又十分之一种武器。一种是标准的 getComputedStyle,另外一种是它的十分之一变种,自恋的M$IE专为自己打造的 currentStyle(哦,据说它的市场份额只有十分之一了嘛)。

在真实的页面中,我们很少见到在元素的 style属性中设置的样式,所以用 style几乎读取不到任何元素的Style。比如下面这个例子:

<style>  body { margin: 10px }</style><body>  <script>    alert(document.body.style.marginTop)  </script> </body>
Copy after login

是得不到任何值的。

这种需求只能靠 window.getComputedStyle来解决,这个方法是 DOM Level 2的标准方法,所有浏览器(除了IE < 9)都支持。

所以要获取上面那个例子中的marginTop,以及所有在浏览器给元素应用了style和样式表之后的Style,都可以像下面这样:

<style>  body { margin: 10px }</style><body>  <script>    var computedStyle = getComputedStyle(document.body, null)    alert(computedStyle.marginTop)  </script></body>
Copy after login

至于IE 9之前的浏览器,就得用 currentStyle读取了。或者像这样:

<style>  body { margin: 10% }</style><body><script>    if (window.getComputedStyle) {      var computedStyle = getComputedStyle(document.body, null)    } else {      computedStyle = document.body.currentStyle    }    alert(computedStyle.marginTop)  </script></body>
Copy after login

好了,上面就是JavaScript征服Style的五种武器。不过我是只用前面四种武器的,既然用户到现在还用IE

声明:本文参考(抄袭)了 Styles and classes, getComputedStyle

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

See all articles