js 学习3

document.getElementsByTagName("a")[0].getAttribute("target");
下面记录一下JS访问CSS中的样式:
用javascript获取和设置style
DOM标准引入了覆盖样式表的概念,当我们用document.getElementById("id").style.backgroundColor 获取样式时 获取的只是id中style属性中设置的背景色,如果id中的style属性中没有设置background-color那么就会返回空,也就是说如果id用class属性引用了一个外部样式表,在这个外部样式表中设置的背景色,那么不好意思document.getElementById("id").style.backgroundColor 这种写法不好使,如果要获取外部样式表中的设置,需要用到window对象的getComputedStyle()方法,代码这样写window.getComputedStyle(id,null).backgroundColor
但是兼容问题又来了,这么写在firefox中好使,但在IE中不好使
两者兼容的方式写成
window.getComputedStyle?window.getComputedStyle(id,null).backgroundColor:id.currentStyle["backgroundColor"];
如果是获取背景色,这种方法在firefox和IE中的返回值还是不一样的,IE中是返回"#ffff99"样子的,而firefox中返回"rgb(238, 44, 34) "
值得注意的是:window.getComputedStyle(id,null)这种方式不能设置样式,只能获取,要设置还得写成类似这样id.style.background="#EE2C21";
在IE中CURRENTSTYLE只能以只读方式获取样式.

本文只为学习,摘录了网络搜索资料结合而成,无任何版权,可以任意转载,如原作者有不同想法,可随时联系我.


用JavaScript修改CSS属性
只有写原生的javascript了。

1.用JS修改标签的 class 属性值:
class 属性是在标签上引用样式表的方法之一,它的值是一个样式表的选择符,如果改变了 class 属性的值,标签所引用的样式表也就更换了,所以这属于第一种修改方法。

更改一个标签的 class 属性的代码是:
document.getElementById( id ).className = 字符串;
document.getElementById( id ) 用于获取标签对应的 DOM 对象,你也可以用其它方法获取。className 是 DOM 对象的一个属性,它对应于标签的 class 属性。字符串 是 class 属性的新值,它应该是一个已定义的CSS选择符。

利用这种办法可以把标签的CSS样式表替换成另外一个,也可以让一个没有应用CSS样式的标签应用指定的样式。

举例:
复制代码 代码如下:

<style type="text/css">
.txt {
font-size: 30px; font-weight: bold; color: red;
}
</style>
<div id="tt">欢迎光临!</div>
<p><button onclick="setClass()">更改样式</button></p>
<script type="text/javascript">
function setClass()
{
document.getElementById( "tt" ).className = "txt";
}
</script>

2.用JS修改标签的 style 属性值:
style 属性也是在标签上引用样式表的方法之一,它的值是一个CSS样式表。DOM 对象也有 style 属性,不过这个属性本身也是一个对象,Style 对象的属性和 CSS 属性是一一对应的,当改变了 Style 对象的属性时,对应标签的 CSS 属性值也就改变了,所以这属于第二种修改方法。

更改一个标签的 CSS 属性的代码是:
document.getElementById( id ).style.属性名 = 值;
document.getElementById( id ) 用于获取标签对应的 DOM 对象,你也可以用其它方法获取。style 是 DOM 对象的一个属性,它本身也是一个对象。属性名 是 Style 对象的属性名,它和某个CSS属性是相对应的。
说明:这种方法修改的单一的一个CSS属性,它不影响标签上其它CSS属性值。
举例:

复制代码 代码如下:
div id="t2">欢迎光临!</div>
<p><button onclick="setSize()">大小</button>
<button onclick="setColor()">颜色</button>
<button onclick="setbgColor()">背景</button>
<button onclick="setBd()">边框</button>
</p>
<script type="text/javascript">
function setSize()
{
document.getElementById( "t2" ).style.fontSize = "30px";
}
function setColor()
{
document.getElementById( "t2" ).style.color = "red";
}
function setbgColor()
{
document.getElementById( "t2" ).style.backgroundColor = "blue";
}
function setBd()
{
document.getElementById( "t2" ).style.border = "3px solid #FA8072";
}
</script>

猜你喜欢

转载自weitao1026.iteye.com/blog/2309445
今日推荐