切换 div 显示隐藏

toggle div to show hide

我有一个简单的代码块 hide/show 两个 div。它工作得很好,我唯一的问题是我需要 return 将 #MSOZoneCell_WebPartWPQ2 的显示值返回到 table。我最初在 css 中将其设置为 none。最后一行好像没有生效

代码如下:

$(function() {
$('#swap').click(function() {

    $('#MSOZoneCell_WebPartWPQ2').toggle();
    $('#example_wrapper').toggle();
    $('#MSOZoneCell_WebPartWPQ').css('display') == 'table';
});
});

您正在使用 == 运算符

试试这个:

$(document).ready(function(){
    $('#swap').click(function() {
        $('#MSOZoneCell_WebPartWPQ2').toggle();
        $('#example_wrapper').toggle();
        $('#MSOZoneCell_WebPartWPQ').attr('style','display:table;');
    });
});

您确定需要“==”来设置值吗?或一个“=”

首先==是一个相等性检查。您应该使用 = 来设置一个值。

其次,css()方法setter接受两个参数。要设置的规则和值本身。试试这个:

$('#MSOZoneCell_WebPartWPQ').css('display', 'table');

你应该使用.css( propertyName, value )

Set one or more CSS properties for the set of matched elements.

所以你的最后一行应该是

$('#MSOZoneCell_WebPartWPQ').css('display', 'table');

当您调用 .css( 属性姓名 )

$('#MSOZoneCell_WebPartWPQ').css('display);

你正在获取所述属性的值而不是设置

Get the computed style properties for the first element in the set of matched elements.


更新 1:

请注意 Jquery 的 .show()、.hide() 和 .toggle() 仅适用于具有块显示的元素 属性。

因此避免来回更改显示 属性 的一种方法是将需要的元素包装在 div(容器)中并 .toggle() 它。

I have created a JSFiddle,我用一个名为 "toggle" 的 calss 将每个 div 扭曲在一个容器 div 中,并将其中一个的初始显示值设置为 "none" 使用样式属性。

<div class="toggle" style="display:none">

现在我使用这个

在它们之间切换
$('.toggle').toggle();

更新 2:

你也可以使用.toggleClass() here's another JSFiddle

将此添加到您的 CSS

#example_wrapper.hiddenDiv, #MSOZoneCell_WebPartWPQ2.hiddenDiv {
  display: none;
}

将 class 添加到您最初想要隐藏的 div

<div id="MSOZoneCell_WebPartWPQ2" class="hiddenDiv">

使用这个

切换class
$(function() {
$('#swap').click(function() {
    $('#MSOZoneCell_WebPartWPQ2').toggleClass("hiddenDiv");
    $('#example_wrapper').toggleClass("hiddenDiv");
});
});

在这个例子中,我使用的是一个名为 "hiddenDiv" 的 class,如果你更改它,请确保 class 名称与 CSS 中的名称相同,HTML 和 JS.