简体   繁体   English

如何使div在一次单击超链接时出现并在再次单击超链接时消失? 可以重复吗?

[英]How to make a div appear when hyperlink is clicked once and disappear when hyperlink is clicked a second time? Can this be repeated?

I am looking for a way to have a div appear after the user clicks a hyperlink, and then have that same div disappear when the user clicks it again. 我正在寻找一种方法,使用户单击超链接后出现div,然后当用户再次单击它时使该div消失。 Currently, the user is only able to have the div appear when the hyperlink is pressed, but when you click the hyperlink again, the div remains in it's "display: block;" 当前,用户只能在按下超链接时使div出现,但是当您再次单击超链接时,该div仍保留在其“ display:block;”中。 state. 州。 Here is what I mean: 这是我的意思:

HTML HTML

<a onclick="showDiv()" id="ShowAboutButton">What's This?</a>

<div id="About">

</div>

CSS CSS

#ShowAboutButton {

    text-align: center;

    margin-top: 40px;

    background-color: white;

    border: none;

    cursor: pointer;

    font-family: "Lato Light";

    font-size: 22px;

}

#About {

    width: 900px;

    height: 600px;

    margin-left: auto;

    margin-right: auto;

    margin-top: 10px;

    background-color: gray;

    display: none;

    transition: height 2s;

}

Javascript 使用Javascript

function showDiv() {

document.getElementById('About').style.display = "block";

}    

If it is at all possible, can someone please show me how to give the user the ability to click the hyperlink and have the div slide in with a transition effect, and then when the hyperlink is clicked again have it slide back out with a transition effect? 如果有可能,请有人告诉我如何赋予用户单击超链接的能力,并使div幻灯片具有过渡效果,然后再次单击超链接时,使其具有过渡的幻灯片向后滑动影响? Any help would be much appreciated! 任何帮助将非常感激! Thank you in advance! 先感谢您!

You can do this very easily with jquery slideToggle : 您可以使用jquery slideToggle轻松完成此slideToggle

$("#ShowAboutButton").click(function(){

    $("#About").slideToggle();

});

JSFIDDLE 的jsfiddle

$('#ShowAboutButton').click(function() {
    $('#About').toggle();
});

OOPS. OOPS。 Missed top of your code. 缺少您的代码顶部。

<a onclick="showDiv(document.getElementById('About'))" id="ShowAboutButton">What's This?   

 <div id="About">
 </div> 

 function showDiv(obj) {
    if(obj.style.display == "block"){
     obj.style.display='none'
    }
    else(obj.style.display == "none"){
     obj.style.display='block'
    }
 }  

Vanilla JavaScript : 香草JavaScript:

var about = document.getElementById('About');
about.style.display='none';

document.getElementById('ShowAboutButton').addEventListener('click', function() {
  //Toggling
  if(about.style.display != 'block') {
return about.style.display='block';
  }
  about.style.display = 'none';

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM