如果我们没有设置过width/height…,我们通过style.width是不能获取到具体的数据
非IE浏览器可以通过”getComputedStyle(需要获取数据的标签对象, false).属性”获取
IE浏览器使用,”标签对象.currentStyle.属性”
**复合样式是不能直接获取,类似于background不能直接获取颜色,需要写为backgroundColor
arguments关键字
如果需要声明任意参数的函数,我们是无法直接实现的
js提供了arguments关键字,它是一个数组,可以保存调用函数时传递过来的所有数据
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>arguments关键字使用</title>
</head>
<body>
</body>
<script>
function foo(){
console.log(arguments);
// 输出arguments保存了多少个参数
console.log('arguments.length = ' + arguments.length);
// 如果长度大于1,输出每一个参数的数据内容
if (arguments.length>1){
console.log('arguments[0] = ' + arguments[0]);
}
}
console.log('无参的调用')
foo();
console.log('有参的调用')
foo(1,2,3,4,5);
foo('A','B','C');
</script>
</html>
封装
/**
* 实现标签对象的样式属性设置或获取
* @param object 需要使用的标签对象(标签对象指的是使用类似document.getElementById得到的结果)
* @param attribute 我们需要操作的样式属性
* @param value 如果是重新设置需要提供这个内容,表示把这个内容设置到样式里
*/
function css(object, attribute, value){
// 在js里函数虽然声明参数,但实际调用过程中可以不提供参数或不提供完整的参数,所以虽要使用arguments判断调用者
// 传递了多少个参数
if(arguments.length == 2){ // 获取
if(object.currentStyle){ // IE浏览器
//object.currentStyle.width;
return object.currentStyle[attribute];
}else{
return getComputedStyle(object, false)[attribute];
}
}else if(arguments.length == 3){ // 设置
object.style[attribute] = value;
// 不能用currentStyle.attribute否则js会认为是调用currentStyle里的attribute属性
}
}
测试
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>utils.js测试</title>
</head>
<body>
<div></div>
</body>
<script type="text/javascript" src="js/utils.js">
// 这里不能添加其他js代码!!!!!!!!!!!!!!!!!!
</script>
<script>
var div = document.querySelector('div');
var width = css(div, 'width');
// alert(width);
console.log('div width is ' + width);
css(div, 'width', '300px');
css(div, 'height', '300px');
css(div, 'border', '1px solid red');
css(div, 'backgroundColor', 'lightgray');
// console.log(css(div, 'background'));
</script>
</html>
下面的内容调用上面的函数
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>非行间样式</title>
</head>
<body>
<div>Hello Kitty</div>
</body>
<script>
/**
* 获取对象的宽度
* @param {Object} obj 需要获取宽度的标签对象
*/
function getWidth(obj){ // 了解
if(obj.currentStyle){ // 如果不是undefined,证明当前浏览器是IE
return obj.currentStyle.width;
}else{ // 结果是undefined,非IE
// getComputedStyle(标签对象, 固定是false);
return getComputedStyle(obj, false).wdith;
}
}
var div = document.querySelector('div');
//console.log('div.style.width = ' + div.style.width);
//var width = getComputedStyle(div, false).width;
//console.log('getComputedStyle(div, false).width = ' + width);
//var width = div.currentStyle.width;
//console.log('div.currentStyle.width = ' + width);
//console.log(div.currentStyle);
console.log(getWidth(div));
</script>
</html>