Heim  >  Artikel  >  Web-Frontend  >  HTML、CSS及JavaScript : JavaScript征服Style的五种武器_html/css_WEB-ITnose

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

WBOY
WBOYOriginal
2016-06-24 11:15:261317Durchsuche

在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>

上面的代码拿到 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=''

上面的代码最终会保持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>

浏览器会对 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>

是得不到任何值的。

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

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

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

至于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>

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

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn