请问为什么点击按钮第一次获得的oMenu.style.display 是空字符串呢?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body style="height:4000px">

<style>
*{

margin: 0;
padding: 0;
list-style: none;
text-decoration: none;

}
button{

width:100px;
display: block;
margin:0 auto;

}
#menu{

width:100px;
margin:0 auto;
overflow: hidden;
clear: both;
display:none;
border:1px solid blue;

}

#menu li{

height: 30px;
line-height: 30px;

}
#menu li#close{

border-top: 1px solid blue;

}

</style>

<button>输入法</button>
<ul id="menu">

<li>手写</li>
<li>拼音</li>
<li id="close">关闭</li>

</ul>

<script>

// get element
var oBtn = document.getElementsByTagName('button')[0];
var oMenu = document.getElementById('menu');
var oClosed = document.getElementById('close');

// public funciton eventEventlist
var eventUil = {

      addHandler : function(obj,type,fn){
        if(obj.addEventListener){
          obj.addEventListener(type,fn,false);
        }else if(obj.attachEvent){
          obj.attachEvent("on"+type,fn);
        }else{
          obj["on"+type] = fn;
        }
      },  

      removeHandler : function(obj,type,fn){
        if(obj.removeEventListener){
          obj.removeEventListener(type,fn,false);
        }else if(obj.detachEvent){
          obj.detachEvent("on"+type,fn);
        }else{
          obj["on"+type] = null;
        }
      }
  }

// funciton about menu display or not

function handler(){
  
   if(oMenu.style.display === "none"){
      oMenu.style.display = "block";
    }else{
      oMenu.style.display = "none";
    }  
}

// function about if you hit the close

function closeMenu(){

  oMenu.style.display = "none";

}

// call addEventlistener

eventUil.addHandler(oBtn,"click", handler)
eventUil.addHandler(oClosed,"click",closeMenu)

</script>

</body>
</html>

阅读 3.6k
3 个回答

ele.style获取到的对象必须是内联申明的样式属性

<div style="diplay:none;"></div>

如果要在获取在css文件中定义的属性则需要调用

window.getComputedStyle(ele, null)[styleName];

来获取,设定第二参数值可以获取伪元素的样式。

IE下的API是:

ele.currentStyle.styleName

因为这样只能获取inline-style

因为在js里dom.style读取的是元素的名为style的attribute,这个值在初始化时并没有从css表里映射到js property中去,所以虽然你写了

#menu{display:none;}

但是

<li id="menu"></li>

的style值是空的,它此时不存在style属性。只有写了:

<li style="display:none;" id="menu"></li>

时,dom.style.display才是有值的。

在读取dom.style时会返回一个根据style属性继承过来的object,如果style属性为空,那么继承过来的object里的style就也是空的

可以改用

window.getComputedStyle

dom.currentStyle

来获取样式表中的值,前者兼容非IE,后者兼容IE(或者其它的情况,我忘记了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题