修複ie8&chrome下window的resize事件多次執行_javascript技巧

來源:互聯網
上載者:User
複製代碼 代碼如下:

/**
* window.onresize 事件 專用事件綁定器 v0.1 Alucelx
* http://www.cnblogs.com/Alucelx/archive/2011/10/20/2219263.html
* <description>
* 用於解決 lte ie8 & chrome 及其他可能會出現的 原生 window.resize 事件多次執行的 BUG.
* </description>
* <methods>
* add: 添加事件控制代碼
* remove: 刪除事件控制代碼
* </methods>
*/
var onWindowResize = function(){
//事件隊列
var queue = [],
indexOf = Array.prototype.indexOf || function(){
var i = 0, length = this.length;
for( ; i < length; i++ ){
if(this[i] === arguments[0]){
return i;
}
}
return -1;
};
var isResizing = {}, //標記可視地區尺寸狀態, 用於消除 lte ie8 / chrome 中 window.onresize 事件多次執行的 bug
lazy = true, //懶執行標記
listener = function(e){ //事件監聽器
var h = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight,
w = window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || document.body.clientWidth;
if( h === isResizing.h && w === isResizing.w){
return;
}else{
e = e || window.event;
var i = 0, len = queue.length;
for( ; i < len; i++){
queue[i].call(this, e);
}
isResizing.h = h,
isResizing.w = w;
}
}
return {
add: function(fn){
if(typeof fn === 'function'){
if(lazy){ //懶執行
if(window.addEventListener){
window.addEventListener('resize', listener, false);
}else{
window.attachEvent('onresize', listener);
}
lazy = false;
}
queue.push(fn);
}else{ }
return this;
},
remove: function(fn){
if(typeof fn === 'undefined'){
queue = [];
}else if(typeof fn === 'function'){
var i = indexOf.call(queue, fn);
if(i > -1){
queue.splice(i, 1);
}
}
return this;
}
};
}.call(this);

綁定window 的 resize 事件,請使用這個對象
樣本:
複製代碼 代碼如下:

var _fn = function(){document.body.innerHTML += "1"};
onWindowResize.add(_fn)
.add(function(){document.body.innerHTML += "2"})
.add(function(){document.body.innerHTML += "3"})
.remove(_fn);
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.