1. 返回检测屏幕宽度(可视区域)
1 function client() {
2 if(window.innerWidth != null) // ie9 + 最新浏览器
3 {
4 return {
5 window.innerWidth,
6 height: window.innerHeight
7 }
8 }
9 else if(document.compatMode === "CSS1Compat") // 标准浏览器
10 {
11 return {
12 document.documentElement.clientWidth,
13 height: document.documentElement.clientHeight
14 }
15 }
16 return { // 怪异浏览器
17 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 常用
外部(使用<link>)和内嵌(使用<style>)样式表中的样式(ie和opera)
2 .window.getComputedStyle("元素", "伪类") w3c
两个选项是必须的, 没有伪类 用 null 替代
3 兼容写法 :
我们这个元素里面的属性很多, left top width ===
我们想要某个属性, 就应该 返回改属性,所有继续封装 返回当前样式的 函数。
1 1 var demo = document.getElementById("demo");
2 2 function getStyle(obj,attr) { // 谁的 哪个属性
3 3 if(obj.currentStyle) // ie 等
4 4 {
5 5 return obj.currentStyle[attr];
6 6 }
7 7 else
8 8 {
9 9 return window.getComputedStyle(obj,null)[attr]; // w3c 浏览器
10 10 }
11 11 }
12 12 console.log(getStyle(demo,"width"));