使用block/none显示/隐藏jquery

Show/hide jquery using block / none

本文关键字:隐藏 jquery 显示 none block 使用      更新时间:2023-09-26

谁能告诉我如何使用这段代码在 DIV 之间显示和隐藏数据(不是隐藏和显示 - 我想要另一种方式)?

我在.js文件中使用:

function toggle(sDivId) {
                var oDiv = document.getElementById(sDivId);
                oDiv.style.display = (oDiv.style.display == "none") ? "block" : "none";
}

在.php文件中:

<div onclick="toggle('divContent1')" style="cursor: pointer;">Hide and show</div>
    <div id="divContent1">
    text here
    </div>
</div>

这段代码工作正常,但是当页面加载时,我希望文本已经隐藏(而不是在我单击"隐藏并显示"文本之后)。

谢谢!

$('#clickMe').click(function(){
 $('#divContent1').toggle();

});

小提琴演示

我可能误解了你的问题,但是如果你想在页面加载时隐藏文本,你不能只贴一个display:none标签,如下所示:

<div id="divContent1" style="display: none">
text here
</div>
您可以使用

您拥有的代码,但只需在 css 中添加display:none;。或者在style="display:none;"里面的 php 中

<div onclick="toggle('divContent1')" style="cursor: pointer;">Hide and show</div>
    <div id="divContent1" style="display:none;">
    text here
    </div>
</div>

jQuery还有一个你可以使用的toogle()函数。

演示

您提供的代码未使用 jquery。如果你想使用 jquery 来做到这一点,你可以把事情改成这样的东西。

function toggle(sDivId) {
    $("#"+sDivId).toggle();
}

在你的 PHP 块中,你需要添加 display:none; 最初隐藏内部div

<div onclick="toggle('divContent1')" style="cursor: pointer;">Hide and show</div>
    <div id="divContent1" style='display:none'>
    text here
    </div>
</div>
您可以使用

toggle()函数在show()和hide()之间交替切换。否则,请直接使用 show () 和 hide () 函数。

调用函数 toggle('divContent1') 在主体的加载事件

<body onload="toggle('divContent1')">

使用以下代码:

function load(){
   document.getElementByID('divContent1').style.display = 'none';
}

并在您的 HTML 中

<body onLoad = "load()">