We're using the following code to show/hide content when an image is clicked:
function toggle(image,list)
{
var listElementStyle=document.getElementById(list).style;
if (listElementStyle.display=="none")
{
listElementStyle.display="block";
document.getElementById(image).src="images/down.png";
document.getElementById(image).alt="Close list";
}
else
{
listElementStyle.display="none";
document.getElementById(image).src="images/up.png";
document.getElementById(image).alt="Open list";
}
}
The function is invoked like this:
<p>
<img src="images/up.png" alt="Open List" id="img39384" onClick="toggle('img39384','ul39384');">Agriculture
<ul id="ul39384" class="catList">
<li>
<a href="databases.jsp?cat=39386">Agriculture - Most Useful</a>
</li>
</ul>
</p>
The first time an "up.png" is clicked, it takes two distinct click to fire-off the script and show/hide content. After that first two-click invocation, a single click will fi开发者_JS百科re the script. This behavior holds true in all browsers--IE, Firefox, Opera, Safari, and Chrome.
What could be causing this behavior?
Your <ul>
element is probably inheriting display: none
from a CSS rule.
However, because the element's style wasn't explicitly set (inline), elem.style.display
is undefined
.
element.style
only contains style properties that are defined in the element's style attribute (i.e., style=""
) and not style properties inherited from <style>
blocks or external CSS files.
Read here for an abstracted way to retrieve style information.
The display value of the element may not be explicitly "none" to start off with. Try this:
function toggle(image,list)
{
var listElementStyle=document.getElementById(list).style;
if (!listElementStyle.display || listElementStyle.display=="none")
{
listElementStyle.display="block";
document.getElementById(image).src="images/down.png";
document.getElementById(image).alt="Close list";
}
else
{
listElementStyle.display="none";
document.getElementById(image).src="images/up.png";
document.getElementById(image).alt="Open list";
}
}
Give your img a
style="display: block;"
attribute when the page loads initially.
精彩评论