web前端 javascript 兼容低版本 IE 6 7 8复合写法

1.  返回检测屏幕宽度(可视区域)

 

 1  function client() {
 2    if(window.innerWidth != null)  // ie9 +  最新浏览器
 3    {
 4       return {
 5          width: window.innerWidth,
 6          height: window.innerHeight
 7       }
 8    }
 9    else if(document.compatMode === "CSS1Compat")  // 标准浏览器
10    {
11       return {
12          width: document.documentElement.clientWidth,
13          height: document.documentElement.clientHeight
14       }
15    }
16    return {   // 怪异浏览器
17       width: document.body.clientWidth,
18       height: document.body.clientHeight
19    }
20 }

 

2. 阻止冒泡 

 w3c的方法是event.stopPropagation()        proPagation  传播  传递

 IE则是使用event.cancelBubble = true       bubble   冒泡  泡泡      cancel 取消

 兼容的写法:

JQuery 阻止时间冒泡   event.stopPropagation();//已经兼容

                          evevt.preventDefault();//阻止浏览器默认行为

 

 

1 2  if(event && event.stopPropagation)
2 3          {
3 4              event.stopPropagation();  //  w3c 标准
4 5          }
5 6          else
6 7          {
7 8              event.cancelBubble = true;  // ie 678  ie浏览器
8 9   }

 

获取你点击的事件源e.target==this作用类似event.stopPropagation();阻止冒泡

1 10  $(".box").on("click",function(e){
2     if(e.target==this){
3         alert("父盒子被点击");
4     }
5 
6 });

3.获取用户选择的内容

window.getSelection()     标准浏览器

document.selection.createRange().text;      ie 获得选择的文字

兼容性的写法:

 

1 if(window.getSelection)
2 {
3     txt = window.getSelection().toString();   // 转换为字符串
4 }
5 else
6 {
7     txt = document.selection.createRange().text;   // ie 的写法
8 }

4. 得到css 样式  

我们想要获得css 的样式, box.style.left    box.style.backgorundColor

但是它只能得到   行内的样式。

但是我们工作最多用的是 内嵌式 或者 外链式

怎么办?

   核心: 我们怎么才能得到内嵌或者外链的样式呢?  

 1.   obj.currentStyle   ie  opera  常用

外部(使用)和内嵌(使用