js特效 - Day3
一、client家族
1.1 clientWidth和clientHeight
網頁可見區域寬: document.body.clientWidth;
網頁可見區域高: document.body.clientHeight;
1.2 clientLeft和clientTop
clientLeft,clientTop
返回的是元素邊框的borderWidth,
如果不指定一個邊框或者不定位改元素,其值就為0
1.3 offset、client和scroll的區別分析
left和top分析:
clientLeft: 左邊邊框的寬度;clientTop: 上邊邊框的寬度
offsetLeft: 當前元素距離有定位的父盒子左邊的距離;offsetTop: 當前元素距離有定位的父盒子上邊的距離
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一般被運用于自適應頁面布局等多屏幕適配場景;
應用:當屏幕的寬度>=960時,頁面的背景顏色為紅色;當屏幕的寬度>=640時,頁面的背景顏色為藍色;當屏幕的寬度<640時,頁面的背景顏色為綠色?
補充:獲取屏幕的分辨率:window.screen.width window.screen.height
四、JS的事件傳遞機制
4.1 冒泡機制
氣泡從水底開始往上升,由深到淺,升到最上面。在上升的過程中,氣泡會經過不同深度層次的水。相對應地:這個氣泡就相當于我們這里的事件,而水則相當于我們的整個dom樹;事件從dom 樹的底層,層層往上傳遞,直至傳遞到dom的根節點。
IE 6.0:
div -> body -> html -> document
其他瀏覽器:
div -> body -> html -> document -> window
注意:不是所有的事件都能冒泡,以下事件不冒泡:blur、focus、load、unload
4.2 阻止冒泡的方法
標準瀏覽器 和 ie瀏覽器
w3c:event.stopPropagation() proPagation 傳播 傳遞
IE:event.cancelBubble = true bubble 冒泡 cancel 取消
兼容的寫法
if(event && event.stopPropagation){ // w3c標準
event.stopPropagation();
}else{ // IE系列 IE 678
event.cancelBubble = true;
}
最新的結論:
新版的谷歌、火狐以及ie的高版本也支持cancelBubble
現在已經新版瀏覽器不存在兼容問題
4.3 獲取當前操作對象
開發中,當執行一個事件時需要去知道觸發這個事件的對象是誰?那么,如何獲取:
火狐、谷歌 event.target
ie 678 event.srcElement
一般是獲取這個對象的id,兼容的寫法如下:
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;
}
- 微博分享
http://v.t.sina.com.cn/share/share.php?searchPic=false&title=' + shareText + '&url=https://github.com/xuanzhihua'
五、綜合動畫函數封裝
在開發過程中,會接觸到很多動畫,比如:幀動畫,核心動畫,轉場動畫......,各種復雜的動畫都是由簡單的動畫封裝而成的,那么,動畫的基本原理是:盒子的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);
}