获取类名的兼容函数
//obj.getElementsByClassName 只能在现代浏览器中使用,不能在IE8以下使用
//两个参数 classname 类名 obj 范围
function getClass(classname,obj){
obj=obj||document;
if(obj.getElementsByClassName){
return obj.getElementsByClassName(classname);// 检测出能在现代浏览器中使用
}else{//在IE8及以下怎么办,获取所有的标签名
var arr=[];
var objs=obj.getElementsByTagName("*");//声明所有的标签用*
for (var i = 0; i < objs.length; i++) {//进行遍历
// if(objs.className==classname){//基本情况
if(checkClass(obj[i].className,classname)){
arr.push(objs[i]);
}
}
return arr;
}
}
//box xi sh 题中有的 用变量classname
//xi val 要找的类名 用变量val
function checkClass(classname,val){
var arr1=obj.split(" ");
for (var i = 0; i < arr1.length; i++) {
if(arr1[i]==val){
return 1;
}
}
return 0;
}
检测结果显示
<div class="box one"></div>
<div class="one"></div>
var one=getClass("one");
console.log(one.length);
将函数进行封装
//我们的目的是 div .box #box
//最后我们要用到$("div") $(".box") $("#box") function(){}
//两个参数 selector 就是div .box #box obj是范围
function $(selector,obj){
var obj=obj||document;
if(typeof selector=="string"){
selector=selector.replace(/^\s*|\s*$/g,"");
if(selector.charAt(0)=="."){
return getClass(selector.slice(1),obj);
}else if(selector.charAt(0)=="#"){
return document.getElementById(selector.slice(1));
}else if(/^[a-zA-Z][a-zA-Z0-8]{0,8}$/.test(selector)){
return obj.getElementsByTagName(selector);
}
}else if(typeof selector=="function"){
window.οnlοad=function(){
selector();
}
}
}
检测结果
<div class="box one"></div>
<div id="one"></div>
<div class="one"></div>
<div class="one"></div>
<div class="one"></div>
var one=getClass("one");
console.log(one.length);
var one=$("#one");
console.log(one);
var one1=$(".one");
console.log(one.length);
var one2=$("div");
console.log(one2.length);
获取样式的兼容函数
//obj.currentStyle() ie
//getComputedStyle() w3c
// 两个参数 obj对象 pro 具体的属性
function getStyle(obj,pro){
if(obj.currentStyle){
return obj.currentStyle[pro];
}else {
return getComputedStyle(obj,null)[pro];
}
}
检测结果
<div class="one"></div>
<div id="one"></div>
<div class="one"></div>
<div class="one"></div>
<div class="one"></div>
.one{
width:200px;
height: 200px;
background: red;
}
var one=$(".one")[0];
console.log(parseInt(getStyle(one,"width")));