0

如果我使用这个 JS 代码:

<script language="javascript" type="text/javascript">
     function showHideDiv()
    {
        var divstyle = new String();
        divstyle = document.getElementById("elementId").style.visibility;
        if(divstyle.toLowerCase()=="visible" || divstyle == "")
        {
            document.getElementById("elementId").style.visibility = "hidden";
        }
        else
        {
            document.getElementById("elementId").style.visibility = "visible";
        }
    }
</script>

然后这是我的 HTML:

<a href="#" class="Action" id="action" onclick="return showHideDiv();">Menu</a>
    <div id="elementId" style="visibility:hidden">
     content here
     </div>

让另一个 div 与另一个扩展 div 但没有多个功能的链接的最佳方法是什么?

4

2 回答 2

0

只需添加一个函数参数:

function showHideDiv(id)
{
    var element = document.getElementById(id),
    visibility = element.style.visibility.toLowerCase(),
    isVisible = visibility === "visible" || visibility === "";

    element.style.visibility = isVisible ? 'hidden' : 'visible';
}

然后在您的 HTML 中,像这样传递它:

onclick="showHideDiv('elementId');"

演示

于 2013-05-13T21:46:57.720 回答
-1

尝试:

function toggleDiv(showDiv) {
    var elm, divstyle, isHidden;
    elm = document.getElementById("elementId");
    divstyle = elm.style.visibility;
    isHidden = divstyle.toLowerCase() == "visible" || divstyle == "" ? false : true;
    elm.style.visibility = (showDiv === true || (isHidden && showDiv !== false) ? 'visible' : 'hidden')
}

用法:

toggleDiv() // Toggles visibility to opposite of current state.
toggleDiv(true) // Always shows div.
toggleDiv(false) // Always hides div.

小提琴:http: //jsfiddle.net/d2jkq/

于 2013-05-13T21:52:26.783 回答