“position”
算是简单的一个控件,可以的话还可以封装一下遮罩层的,工作中都已经有封装好的组件,就不多此一举。
var setPosition = (function () {
var docElem = window.document.documentElement,
body = window.document.body,
docWidth = docElem.clientWidth,
docHeight = docElem.clientHeight;
return {
capitalize: function (str) {
var firstStr = str.charAt(0);
return firstStr.toUpperCase() + str.replace(firstStr, '');
},
getScroll: function (type) {
var upType = this.capitalize(type);
return docElem['scroll' + upType] || body['scroll' + upType];
},
// 初始化位置
init: function (id) {
var ele = document.getElementById(id),
eWidth = ele.offsetWidth,
eHeight = ele.offsetHeight,
widthOverflow = eWidth > docWidth,
heigthOverflow = eHeight > docHeight;
ele.style.position = 'absolute';
ele.style.top = docElem.clientHeight / 2 + this.getScroll('top') + 'px';
ele.style.left = docElem.clientWidth / 2 + this.getScroll('left') + 'px';
ele.style.marginLeft = '-' + (widthOverflow ? docWidth / 2 : eWidth / 2) + 'px';
ele.style.marginTop = '-' + (heigthOverflow ? docHeight / 2 : eHeight / 2) + 'px';
}
}
})();
capitalize是首字母大写转化的函数。 getScroll就是计算网页被卷起来的top和left值 然后init就是具体的赋值了。
需要使用的时候直接这样就可以调用。
setPosition.init(‘djdj’)