6-7 这样写会不会把参数写的太死了 有什么更好的方法吗
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title> arguments</title>
</head>
<body>
<p id="test" style="background-color: red; color: blue;">我是一个段落!</p>
<script type="text/javascript">
function cssStyle(p,name,value){
arguments[0] = document.getElementById('test');
arguments[1] = 'style';
if(arguments.length <= 2){
return p.getAttribute(name);
}else{
return p.setAttribute(name,value)
}
}
cssStyle("background:orange");
document.write(cssStyle('color'));
cssStyle(1,2,'background-color:yellow');
</script>
</body>
</html>
正在回答 回答被采纳积分+1
1.函数的参数可以理解为函数内部的变量。
function cssStyle(p){}在解析的时候相当于
function cssStyle(p){var p=undefined}
//所以,在创建函数的时候p已经成为第一个参数,即p=arguments[0];对p进行操作 即可,对arguments[0]进行具体的赋值,相当于对p进行的具体的赋值。而p是参数,对参数赋值,那还传它有啥用呢??
<body>
<p id="test" style="background-color: red; color: blue;">我是一个段落!</p>
<p id="test1" style="background-color: lawngreen; color: #000;">我是一个段落!</p>
<p id="test2" style="background-color: yellow; color: blue;">我是一个段落!</p>
<script type="text/javascript">
function cssStyle(Tagname,stylename,value) {
var Tag_obj = document.getElementById(Tagname);
if(arguments.length===1){//如果只传入标签的id名返回所有style样式,
return Tag_obj.style.cssText;
}else if(arguments.length===2){//如果这个参数有传入样式名但没有传入值 ,则返回当前标签的所有样式属性
return Tag_obj.style[stylename];
}else{
Tag_obj.style[stylename]=value;//如果传入的都有值,那么设置样式;
}
}
console.group(cssStyle('test'))
console.log(cssStyle('test1','backgroundColor'))
cssStyle('test2','backgroundColor','#ff5555')//
</script>
</body>
- 参与学习 1887 人
- 提交作业 4643 份
- 解答问题 5760 个
有HTML和CSS基础,却不知道如何进阶?本路径带你通过系统学习,完成从“会做网页”到“做出好的动态网页”的蜕变,迈出成为前端工程师的第一步。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星