日期:2014-05-16  浏览次数:20588 次

js、css可能出现的一个问题:【js得到已设置属性为空】

? ? ? ? 最近在做一些js实例应用,发现了一个奇怪的问题。下面是过程:

①按钮:

②点击后

--------------------------------------------------------------

这个在我看来非常容易,于是我很快就写好了:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
*{margin:0; padding:0;}
#outer{ margin:50px auto; width:70px;}
#button1{ padding:5px 8px; cursor:pointer;}
#inner{ border:1px solid blue; border-radius:5px; display:none; font-family:"新宋体"; font-size: 
12px;}
#inner li{ padding:5px 8px; border-bottom:1px solid blue; list-style-type:none; display:inline-block; 

cursor:pointer; vertical-align:top; width:52px;}
#inner li.last{border-bottom:0px;}
#inner li a{text-decoration:none;}
#inner li:hover{background:#afafaf;}
</style>
<script>
window.onload = function ()
{
	oButton=document.getElementById("button1");//按钮
	oAppend=document.getElementById("inner");//按钮下的蓝色边框区域。
	oButton.onclick=function()
	{
		switchState();
	}
	
	var oClose=document.getElementById("last");
	oClose.onclick=function()
	{
		switchState();	
	}
}
var oButton;
var oAppend;

var switchState = function()//①当蓝色区域未显示时使其显示、②当蓝色区域显示时使其消失。
{
	//alert("PRE: [display] = "+oAppend.style["display"]);
	oAppend.style["display"]= (oAppend.style["display"] == "none"?"block":"none");
	//alert("NOW: [display] = "+oAppend.style["display"]);
}
</script>
<body>
<div id="outer">
	<button id="button1">输入法</button>
	<ul id="inner">
		<li><a href="javascript:void(0);">拼音</a></li>
		<li><a href="javascript:void(0);">字母</a></li>
		<li id="last"><a href="javascript:;">关闭</a></li>
	</ul>
</div>
</body>
</html>

?--------

可是,当我运行时却发现第一次点击按钮时,蓝色区域并不会弹出来,而后的点击才有效。这是为什么呢?

----于是在上述代码中我将【oAppend.style["display"](即蓝色区域的display属性)】输出,发现第一次点击时,程序运行到了switchState()方法。但是display属性为null。

-------

经过查询,原来外部样式表与内页样式的属性值虽然已经设置,但是js的方法不能直接得到已设置属性的值,即显示为null。而只能得到行内样式中的属性值。

------

解决方法:①将switchState()的判断顺序改变一下->

var switchState = function()
{
	//alert("PRE: [display] = "+oAppend.style["display"]);
	oAppend.style["display"]= (oAppend.style["display"] == "block"?"none":"block");
	//alert("NOW: [display] = "+oAppend.style["display"]);
}

这样第一次点击时就先判断显示,若未显示就将其显示。?

②?在对应元素的标签中嵌入【style="display:none"】

这样第一次点击时判断语句就能得到oAppend.style["display"]的值为【“none”】而不是【null】了。
?

?