web前端之瀏覽器篇——兼容各種瀏覽器常用的原生js工具類
一、獲取瀏覽器可見域的寬高(不包括滾動條和被捲去)
ieE<=8 不支持innerWidth和innerHeight屬性,ie6支持
document.documentElement.clientHeight,其他ie版本用document.body.clientHeight
export function getWinHeight() {
var windowHeight;
if (window.innerHeight) { // 除了IE 8 以外的瀏覽器
windowHeight = window.innerHeight
} else if (document.documentElement && document.documentElement.clientHeight) { /* IE6 瀏覽器 */
windowHeight = document.documentElement.clientHeight
} else if (document.body) { //其他版本的IE瀏覽器
windowHeight = document.body.clientHeight
}
return windowHeight;
}
export function getWinWidth() {
var windowWidth;
if (window.innerWidth) { // 除了IE以外的瀏覽器
windowWidth = window.innerWidth
} else if (document.documentElement && document.documentElement.clientWidth) { /* IE6 瀏覽器 */
windowWidth = document.documentElement.clientWidth
} else if (document.body) { //其他版本的IE瀏覽器
windowWidth = document.body.clientWidth
}
return windowWidth;
}
clientHeight/Width指如下:
二、事件的添加與移除
ieE<=8 不支持document.addEventListener事件添加與document.removeEventListener事件移除
export const on = (function() {
if (document.addEventListener) {
return function(element, event, handler) {
if (element && event && handler) {
element.
(event, handler, false);
}
};
} else {
return function(element, event, handler) {
if (element && event && handler) {
element.attachEvent('on' + event, handler);
}
};
}
})();
export const off = (function() {
if (document.removeEventListener) {
return function(element, event, handler) {
if (element && event) {
element.removeEventListener(event, handler, false);
}
};
} else {
return function(element, event, handler) {
if (element && event) {
element.detachEvent('on' + event, handler);
}
};
}
})();
三、獲取滾動條寬
ie不支持瀏覽器滾動條的設定與獲取。elementUI2.13.2版本中獲取滾動條方法如下:
export scrollbarWidth function() {
const outer = document.createElement('div');
outer.className = 'el-scrollbar__wrap';
outer.style.visibility = 'hidden';
outer.style.width = '100px';
outer.style.position = 'absolute';
outer.style.top = '-9999px';
document.body.appendChild(outer);
const widthNoScroll = outer.offsetWidth;
outer.style.overflow = 'scroll';
const inner = document.createElement('div');
inner.style.width = '100%';
outer.appendChild(inner);
const widthWithScroll = inner.offsetWidth;
outer.parentNode.removeChild(outer);
scrollBarWidth = widthNoScroll - widthWithScroll;
return scrollBarWidth;
};