zl程序教程

您现在的位置是:首页 >  其他

当前栏目

IE及firefox下获取及设置样式值的代码

代码 设置 获取 IE 样式 firefox
2023-06-13 09:14:17 时间
复制代码代码如下:

<scripttype="text/javascript">
//<![CDATA[
function$(obj)
{
returndocument.getElementById(obj);
}
functiongetStyle(obj,styleName)
{
if(obj.currentStyle)//fories
{
returnobj.currentStyle[styleName];//注意获取方式
}
else//forothers
{
returndocument.defaultView.getComputedStyle(obj,null).getPropertyValue(styleName);
//returndocument.defaultView.getComputedStyle(obj,null)[styleName];
}
}
$("btnGetClick").onclick=function()
{
//直接写在tag上的为内嵌样式、写在head-style里的为内部样式、link引入的为外部样式
//内嵌样式,可以通过Dom.style.样式名称获取,需要注意的是样式名称是驼峰格式
//内部样式和外部样式通过style.样式名称是无法获取到的,需要通过currentStyle||getComputedStyle来获取
//其实,这很好理解,内嵌样式的时候,tag具有style属性(该属性值返回的是object对象),那我们就可以通过style.样式名称来获取
//而内部或外部时,虽有style属性,但相应的值为空,所以就只有通过currentStyle||getComputedStyle来获取
//alert($("div2").style);可以看到,弹出的结果为object,说明style是存在的,只是其下的相应样式设置为空而已。
$("testContent").innerHTML="";
varstr=$("div").style.styleFloat||$("div").style.cssFloat;//因为float是保留词,因此,不能再style.float,而用ies:styleFloat,ff:cssFloat
str=str+($("div").style.width+"<br/>");
str=str+($("div2").style.width+"<br/>");//这一段无法获取到内部样式,显示空值,但并不是说style不存在
str=str+($("div2").width+"<br/>");//返回undefined,因为没有为div2的dom设置width属性
str=str+getStyle($("div2"),"width");//div2的样式是通过内部样式提供,因此通过currentStyle||getComputedStyle来获取
$("testContent").innerHTML=str;
}
$("btnUpdateClick").onclick=function()
{
//设置样式时,不管是内嵌、内部还是外部,反正这3种方式,都可以获取到style属性(对象)
//那就可以通过它为元素设置样式,设置样式的办法有以下3种
$("div").style.width="200px";
$("div2").style.width="100px";
$("div").style.cssText="background:blue;color:red;font-weight:bold;";//将覆盖原来的定义,相当于定义style="background:blue;font-size:red;font-weight:bold;"
$("div2").className="testClassName";//相当于设置<divclass="testClassName"/>
}
//]]>
</script>

演示代码:

TestbyMcJeremy&Xu #div2 { width:200px; height:100px; margin-left:120px; border:1pxdashedblue; } .testClassName { background:red; } Div1
Div2
获取值 设置值