javascript不定参数&&兼容性样式设置与获取

来源:互联网 发布:机箱推荐 知乎 编辑:程序博客网 时间:2024/05/16 19:31
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>不定参数/可变参数</title><style type="text/css">#div1{width: 100px;height: 100px;background-color:#FF0000;}</style></head><script type="text/javascript">function add(){//可以不定参数//alert(arguments.length);//输出参数的个数var sum=0;var i=0;for(i=0;i<arguments.length;i++){//加法计算sum+=arguments[i];}return sum;}function show(){//alert(arguments.length);//输出参数的个数//设置层的颜色if(arguments[0].currentStyle){//IEalert(arguments[0].currentStyle["background-color"]);}else{//Firefox,chromealert(window.getComputedStyle(arguments[0],false).getPropertyValue("background-color"));//window.getComputedStyle(arguments[0],false)["background-color"];//firefox不支持}}//获取属性,或者设置属性,function objectStyle(obj,attr,value){if (arguments.length==2)//当参数为obj,attr为获取属性值{if (attr.currentStyle) {//IEreturn obj.currentStyle[attr];}else{//othersreturn window.getComputedStyle(obj,false).getPropertyValue(attr);}}else if(arguments.length==3){//当参数为obj,attr,value为设置属性值obj.style[attr]=value;}}window.onload=function(){//alert(add(1,2,3,4,5,6,7,8,9,10));//调用不定参数的加法运算var oBtnGetColor=document.getElementById("btnGetColor");//获取层颜色var oBtnSetColor=document.getElementById("btnSetColor");//设置层的颜色var oBtnSetWidth=document.getElementById("btnSetWidth");//修改层的宽度var oDiv=document.getElementById("div1");oBtnGetColor.onclick=function(){//获取层的颜色show(oDiv);};oBtnSetColor.onclick=function(){objectStyle(oDiv,"background-color","green");//修改层的颜色};oBtnSetWidth.onclick=function(){//修改层的宽度objectStyle(oDiv,"width","200px");};};</script><body><input id="btnGetColor" type="button" value="获取层的颜色" /><input id="btnSetColor" type="button" value="修改层的颜色" /><input id="btnSetWidth" type="button" value="修改层的宽度" /><div id="div1"></div></body></html>

0 0
原创粉丝点击