javascript - 请问为什么点击按钮第一次获得的oMenu.style.display 是空字符串呢?
怪我咯
怪我咯 2017-04-11 09:42:27
[JavaScript讨论组]

<!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)
ringa_lee

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

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

如果要在获取在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(或者其它的情况,我忘记了

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号