jquery里有一个 toggle 函数,可以切换显示与隐藏,
而我自己一般都是判断 obj.style.display 的值是否为 none ,
如果是,就用 obj.style.display = "" 将 none 属性去掉,
如果不是,就加上 display = "none" ,可是如果属性 display:none 在外部样式中,就会出错,读取不到,后来又用了 currentStyle.display 读取,火狐下用 getComputedStyle 方法,
但是还有一个问题就是,如果样式为 display:none; ,那我要怎么显示呢?
因为显示一般用到两种,block 和 inline ,如何判断用block还是inline 呢?
而我自己一般都是判断 obj.style.display 的值是否为 none ,
如果是,就用 obj.style.display = "" 将 none 属性去掉,
如果不是,就加上 display = "none" ,可是如果属性 display:none 在外部样式中,就会出错,读取不到,后来又用了 currentStyle.display 读取,火狐下用 getComputedStyle 方法,
但是还有一个问题就是,如果样式为 display:none; ,那我要怎么显示呢?
因为显示一般用到两种,block 和 inline ,如何判断用block还是inline 呢?
document.getElementById('ceng').style.display = "block";
}
每次这样用都是好的啊
如果html的代码是这样的,以上的js代码就不怎么好用了。。
-----------------------------
<style type="text/css">
#ceng {
display: none;
}
</style><div id="ceng" style="width:100px;height:100px;background-color:green"></div>
-----------------------------
这时用 document.getElementById('ceng').style.display 得到的值是空,而不是"none";或者:
-----------------------------
今年是 <span id="ceng" style="display:none;">2011</span> 年
-----------------------------
这样执行js的时候就会多出换行的效果。。
问题是,如果现在已经是 display:none 了呢?
我在css文件里写 display:none ,表示这一类默认是不显示的,只在需要的时候显示。
<style>
#ceng {
display: none;
}
</style><div id="ceng" style="width:100px;height:100px;background-color:green">aaa</div><input type=button onclick="if(document.getElementById('ceng').style.display=='none'||document.getElementById('ceng').style.display=='')document.getElementById('ceng').style.display='block';else document.getElementById('ceng').style.display='none';" value="theforever切换显示">
看来我还是没有表达清楚啊我想做这样一个功能:
1. 切换显示与隐藏; 其实就是jQuery里的 $().toggle() 这样的效果,我想自己写;
2. 事先并不知道该元素的初始状态是显示还是隐藏的,也就是说,并不知道 #ceng{} 里的display 属性一定是none值,楼上的代码已经假定如果 obj.style.display 为空的话,就当作初始状态是隐藏的;
3. 希望可以自动判断是行内元素还是块状元素,
如果事先元素是隐藏的,那么在呈现的时候按其缺省值来,
div 加 display:block;
span 加 display:inline;
还有其他元素
不知道的是块状元素还是内联元素对吧
其实不用判断的。display = '';那么如果是内联元素 就会计算成inline
如果是块级元素 就是block
嗯,
写在外部样式表的 display:none 不能使用 document.getElementById().style.display 读取,
但可以用 document.getElementById().currentStyle.display (IE)
火狐里用 window.getComputedStyle(obj , null).display 这种方式;加 display = '' ,对于以下情况就不行了啊:<style type="text/css">
#ceng { display: none; }
</style><div id="ceng"
style="width:100px; height: 100px; background-color: green; display:;" >
</div>
这里,有两个display属性,内部样式里的 display:none;,和内嵌样式里的 display:;,
本来应该是内嵌样式优先的,
可是内嵌样式给的是空字符串,
它会去找 #ceng{} 里定义的 display:none,
所以,给div加 style.display = '' ,也并不会让div显示出来。