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;
};