函数return/获取元素样式/封装自己的库

时间:2023-03-08 17:30:14
函数return/获取元素样式/封装自己的库

一:函数return

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
 
<script>
 
// return 返回值
// 数字、字符串、布尔、函数、对象(元素\[]\{}\null)、未定义
 
// fn1();函数名称加括号等于return后面的值 无论后面是什么类型的值甚至是函数 => 100
// alert( fn1().length );
// alert( typeof fn1() );
function fn1(){
// return 100;
return 'miaov';
}
 
// alert( fn2() );
 
// fn2(20)(10);
function fn2(a){
return function (b){
alert(a+b); // 嘿嘿,我是注释~
};
}
 
fn3().onload = function (){
document.body.innerHTML = 123;
};
 
function fn3(){
return window;
}
 
// alert(fn4());
function fn4(){
// return ;
}
 
// alert( fn5() );
function fn5(){
return 123;
alert(520);
}
 
/*
return:返回值
1) 函数名+括号:fn1() ==> return 后面的值;
2) 所有函数默认返回值:未定义;
3) return 后面任何代码都不执行了;
*/
 
</script>
 
</head>
 
<body>
</body>
</html>
二:获取元素样式/
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
div { width:100px; height:120px; background:red; }
</style>
<script src="miaov.js"></script>
<script>
$(function(){
// $('div1').style.width = '300px';只能获得行间的style with 不能得到样式表中的with.
$('btn1').onclick = function (){
// alert( $('div1').style.width );
// $('div1').style.cssText = 'width:350px;';
// alert( getComputedStyle( $('div1') ).width );
// IE6 7 8 不兼容,直接在IE9中的汉语调试工具中测试即可,左右两个标准
// alert( $('div1').currentStyle.width ); // 兼容IE678,但是标准浏览器比如火狐不兼容
/*
if( $('div1').currentStyle ){
alert( $('div1').currentStyle.width );
} else {//解决浏览器兼容问题,属性判断法,版本检测法,很多解决问题。
alert( getComputedStyle( $('div1'), 250 ).width );
// FF 4.0 之前,现在都38.1版本了,联网自动更新的。
}
*/
// alert( getStyle( $('div1'), 'width' ) );
// alert( getStyle( $('div1'), 'height' ) );
alert( getStyle( $('div1'), 'marginRight' ) );
/* alert( getStyle( $('div1'), 'width' ) );
获取到的是计算机(浏览器)计算后的样式也就是真实的
background: url() red …… 复合样式(不要获取)
backgroundColor 单一样式(不要用来做判断)
//能弹出不同的颜色了。IE red火狐chromerrgba(255,0,0)
不要有空格,不然全是undefine
不要获取未设置后的样式:不兼容getStyle( $('div1'), 'marginRight' )
*/
};
});
</script>
</head>
<body>
<input id="btn1" type="button" value="按钮" />
<div id="div1"></div>
</body>
</html>
三:封装自己的库
<script src="miaov.js"></script>
function $( v ){
if( typeof v === 'function' ){
window.onload = v;
} else if ( typeof v === 'string' ) {
return document.getElementById(v);
} else if ( typeof v === 'object' ) {
return v;
}
}
 
function getStyle( obj, attr ){
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle( obj )[attr];
}