/ Published in: JavaScript
Expand |
Embed | Plain Text
var $ = function(id) { return document.getElementById(id); }, // 触点 html = document.documentElement, box = $('cnt'), posX = $('left'), posY = $('top'), width = $('width'), height = $('height'), // 浮动框大小 boxWidth = box.offsetWidth, boxHeight = box.offsetHeight, // 设置位置 setPos = function() { // 可视窗口 var htmlWidth = html.clientWidth, htmlHeight = html.clientHeight, // margin 值 marginX = htmlWidth > boxWidth ? -(boxWidth/2) : 0, marginY = htmlHeight > boxHeight ? -(boxHeight/2) : 0, // 可视宽度如果太小,要注意让内容能完整显示出来 left = marginX == 0 ? 0 : '50%', top = marginY == 0 ? 0 : '50%'; box.style.left = left; box.style.top = top; box.style.marginLeft = marginX + 'px'; box.style.marginTop = marginY + 'px'; }, // 找到位置 getPos = function() { var curLeft =0, curTop = 0, obj = box; if (obj.offsetParent) { while (obj.offsetParent) { curLeft += box.offsetLeft; curTop += box.offsetTop; obj = obj.offsetParent; } } posX.innerHTML = curLeft; posY.innerHTML = curTop; }; width.innerHTML = boxWidth; height.innerHTML = boxHeight; setPos(); getPos(); // 用户放大/缩小窗口,浮动应做相应处理 window.onresize = function(){ setPos(); getPos(); }
You need to login to post a comment.
