首页 文章

JS在第一次点击时切换DIV CSS中的更改

提问于
浏览
0

Background 我有3个ASP按钮,每个按钮都使用DIV ID参数调用相同的JavaScript . 触发时,JS应该切换已传递ID的DIV的display属性 .

Problem 第一次单击该按钮时,没有任何反应 . 在随后的点击中,一切似乎都很好:如果DIV是'block',则设置为'none',反之亦然 .

Code 对于按钮:

<button id="pdp_section_a_button" Class="pdp_section_button" onclick="Show_Hide_Display('<%=pdp_section_a_div.ClientID%>');return false">Section A</button>
    <button id="pdp_section_b_button" Class="pdp_section_button" onclick="Show_Hide_Display('<%=pdp_section_b_div.ClientID%>');return false">Section B</button>
    <button id="pdp_section_c_button" Class="pdp_section_button" onclick="Show_Hide_Display('<%=pdp_section_c_div.ClientID%>');return false">Section C</button>

对于JS函数:

<script type="text/javascript">

    function Show_Hide_Display(divID) {

        alert(document.getElementById(divID).style.display); // on first click this is blank, on other clicks the DIV's current display property is shown

        var div = document.getElementById(divID);

        if (div.style.display == "" || div.style.display == "block") {
            div.style.display = "none";
        }
        else {
            div.style.display = "block";
        }

        return false;
    }

</script>

1 回答

  • 2

    element.style 仅显示内联样式,而不显示活动的css属性 .

    为了获得活动的css,请使用以下内容 .

    var div = document.getElementById(divID);
    var style = document.defaultView.getComputedStyle(div);
    // equivalent to window.getComputedStyle
    
    var display = style.getPropertyValue('display');
    if (display == '' || display == 'block') {
        div.style.display = 'none';
    } else {
        div.style.display = 'block';
    }
    

相关问题