js弹出居中 滚动条和窗口变化

原创 emily2013 随笔 js 310阅读 2017-05-26 10:33:07 举报

function center(obj) {
var screenWidth = document.documentElement.clientWidth, screenHeight = document.documentElement.clientHeight; //当前浏览器窗口的 宽高
var scrolltop = document.body.scrollTop;//获取当前窗口距离页面顶部高度
var objLeft = (screenWidth - obj.offsetWidth)/2 ;
var objTop = (screenHeight - obj.offsetHeight)/2 + scrolltop;
obj.style.cssText = 'left:' + objLeft + 'px;top:' + objTop + 'px;';
//浏览器窗口大小改变时
window.onresize = function () {
var screenWidth = document.documentElement.clientWidth, screenHeight = document.documentElement.clientHeight; //当前浏览器窗口的 宽高
var scrolltop = document.body.scrollTop;//获取当前窗口距离页面顶部高度
var objLeft = (screenWidth - obj.offsetWidth)/2 ;
var objTop = (screenHeight - obj.offsetHeight)/2 + scrolltop;
obj.style.cssText = 'left:' + objLeft + 'px;top:' + objTop + 'px;';
}
//浏览器有滚动条时的操作、
$(window).scroll(function() {
var screenWidth = document.documentElement.clientWidth, screenHeight = document.documentElement.clientHeight; //当前浏览器窗口的 宽高
var scrolltop = document.body.scrollTop;//获取当前窗口距离页面顶部高度
var objLeft = (screenWidth - obj.offsetWidth)/2 ;
var objTop = (screenHeight - obj.offsetHeight)/2 + scrolltop;
obj.style.cssText = 'left:' + objLeft + 'px;top:' + objTop + 'px;';
});
}

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复