JavaScript 遮罩层与弹出层

*Element.style.width(height)只能获取HTML中的宽和高(无法获取CSS中的样式),并且宽和高为带'px'的字符串

*Element.offsetHeight(offsetWidth)需要在该元素插入HTML中之后(新创建的元素)才能获取到

 

遮罩层与弹出层(登录框)使用fixed定位,遮罩层使用设备分辨率的宽高

 

function openNew(){
  //获取设备分辨率的高度和宽度
  var sWidth=window.screen.width;
  var sHeight=window.screen.height;
  //获取页面的可视区域高度和宽度
  // var wHeight=document.documentElement.clientHeight;
  // var wWidth=document.documentElement.clientWidth;
  var oMask=document.createElement("div");
  oMask.id="mask";
  oMask.style.height=sHeight+"px";
  oMask.style.width=sWidth+"px";
  document.body.appendChild(oMask);
  var oLogin=document.createElement("div");
  oLogin.id="login";
  oLogin.innerHTML="<div class='loginCon'><div id='close'>点击关闭</div></div>";
  document.body.appendChild(oLogin);
  //获取登陆框的宽和高
  var dHeight=oLogin.offsetHeight;
  var dWidth=oLogin.offsetWidth;
  //设置登陆框的left和top
  oLogin.style.left=sWidth/2-dWidth/2+"px";
  oLogin.style.top=sHeight/2-dHeight/2+"px";
  //点击关闭按钮
  var oClose=document.getElementById("close");
  //点击登陆框以外的区域也可以关闭登陆框
  oClose.onclick=oMask.onclick=function(){
    document.body.removeChild(oLogin);
    document.body.removeChild(oMask);
  };
};
window.onload=function(){
  var oBtn=document.getElementById("btnLogin");
  //点击登录按钮
  oBtn.onclick=function(){
    openNew();
    return false;
  }
}

posted @ 2016-01-07 14:45  inethard  阅读(329)  评论(0编辑  收藏  举报