一.client家族
1.1.clientWidth 和 clientHeight
網頁可見區域寬:document.body.clientWidth
網頁可見區域高:document.body.clientHeight
1.2clientLeft 和 clientTop
clientLeft , clientTop
返回的是元素邊框的borderWidth
如果不指定一個邊框或者不定位該元素,其值就為0
1.3offset? client 和scroll的區別分析
left 和 top分析:
? ? ? ? ?clientLeft :左邊邊框的寬度;clientTop:上邊邊框的寬度
? ? ? ? offsetLeft:當前元素距離有定位的父盒子左邊的距離;offsetTop:當前元素距離有定位的父盒子上邊的距離(如果沒有父元素或父元素都沒有定位,就以body為參照)
? ? ? ? scrollLeft:左邊滾動的長度;scrollTop:上邊滾動的長度;
width和height分析:
clientWidth/Height:內容+內邊距
offsetWidth/Height:內容+內邊距+邊框
scrollWidth/Height:滾動內容的寬度和高度
二.獲取屏幕的可視區域
ie9+ 和 最新瀏覽器
window.innerWidth,window.innerHeight
標準模式瀏覽器
document.documentElement.clientWidth,document.documentElement.clientHeight;
怪異模式
document.body.clientWidth,document.body.clientHeight;
通用寫法
function client() {
if(window.innerWidth){ // ie9及其以上的版本
return{
width: window.innerWidth,
height:? window.innerHeight
}
}else if(document.compatMode != 'CSS1Compat'){? // 怪異模式
return{
width: document.body.clientWidth,
height: document.body.clientHeight
}
}
// 標準
return{
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
}
}
三.常用窗口事件-onresize
當窗口或框架的大小發生改變的時候就會調用;
onresize一般被運用于自適應頁面布局等多屏幕適配場景;
應用:當屏幕的寬度>=900時,頁面的背景顏色為紅色;當屏幕的寬度>=600時,頁面的背景顏色為綠色;當屏幕的寬度<600時,頁面的背景顏色為藍色
補充:獲取屏幕的分辨率
window.screen.height
window.screen.width
四.JS的事件傳遞機制
4.1冒泡機制
起泡從水底開始往上升,由深到淺,升到最上面.在上升的過程中,起泡會經過不同深度層次的水.
這個起泡就相當于我們這里的事件,而水則相當于我們的整個dom樹,事件從dom樹的底層,層層往上傳遞,直至傳遞到dom的根節點.
IE6.0:
div-->body-->html-->document-->window
注意點:不是所有的事件都能冒泡,以下事件不冒泡:blur.focus.load.unload
4.2阻止冒泡的方法
標準瀏覽器和ie瀏覽器
W3c:event.cancelBubble=true
兼容寫法:
var event = event || window.event;
if(event.stopPropagation){ // w3c標準
event.stopPropagation();
}else{ // IE系列 IE 678
event.cancelBubble = true;
}
4.3獲取當前操作對象
開發中,當執行一個事件時需要去知道觸發這個事件的對象是誰,
火狐.谷歌 event.target
ie? 678 event.srcElement
一般是獲取這個對象的id 兼容寫法如下:
js var targetId = event.target ? event.target.id : event.srcElement.id;
4.4 獲取用戶選中的內容
標準瀏覽器
window.getSelection()
ie獲得選擇的文字
document.selection.createRange().text
兼容寫法:
var selectedText;
if(window.getSelection){ // 標準模式 獲取選中的文字
selectedText = window.getSelection().toString();
}else{ // IE 系列
selectedText = document.selection.createRange().text;
}
打開新的窗口:
js /* * 第一個參數是url * 第二個參數是窗口的名稱 要不要打開新的窗口 * 第三個參數是窗口的描述 窗口的位置,尺寸等 * */ window.open('http://www.lxweimin.com/u/ce8eba0dbfb6','newWindow','left=500,top=200,width=800,height=500');
五.綜合動畫函數封裝
在開發過程中,會用到很多動畫,比如:幀動畫,核心動畫,轉場動畫......各種復雜的動畫都是由簡單的動畫封裝而成的,動畫的基本原理是:盒子的offsetLeft+步長
勻速動畫函數封裝:
function animate(obj, target, speed) {?
// 1.清除定時器 clearInterval(obj.timer);?
// 2. 判斷方向 var dir = target > obj.offsetLeft ? speed : -speed; obj.timer = setInterval(function () { obj.style.left = obj.offsetLeft + dir + 'px';?
// 2.1 清除定時器 --> offsetLeft == 目標值 if (Math.abs(target - obj.offsetLeft) <= speed) { clearInterval(obj.timer);
?// 處理偏差情況 obj.style.left = target + 'px'; } }, 10); }