在单击图标上显示div,然后再次单击隐藏Div

时间:2018-09-18 00:16:21

标签: javascript jquery html css

我有一个带有搜索图标的导航栏。当我单击它时,我希望它显示一个具有输入和按钮的div,如果再次单击相同的图标,则希望隐藏相同的div。到目前为止,当我单击它时,它会显示div,但是当我再次单击它时,它不会将其关闭。

<form class="form-inline my-2 my-lg-0">
    <i id="searchIcon" class="fas fa-search fa-2x">&nbsp;&nbsp;</i>
    <div  style="display:none" class="input-group date" id="searchDate" data-target-input="nearest">
        <input type="text" class="form-control datetimepicker-input" id="datetimepicker6" data-toggle="datetimepicker" data-target="#datetimepicker6"/>&nbsp;&nbsp;
        <button class="btn btn-outline-info my-2 my-sm-0" type="submit">Search</button>
    </div>
    <a style="color: black" href="logout.php"><i class="fas fa-sign-out-alt fa-2x"></i></a>
</form>

还有我的javascript:

    $('#searchIcon').click(function(){
        console.log("searcg clicked");
        this.click?$('#searchDate').show(1000):$('#searchDate').hide(1000);
    }); 

有人知道为什么它无法关闭吗?

3 个答案:

答案 0 :(得分:4)

jQuery带有toggle方法:

$('#searchIcon').click(function() {
  $("#searchDate").toggle("slow");
});
@import url("https://use.fontawesome.com/releases/v5.3.1/css/all.css");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form class="form-inline my-2 my-lg-0">
  <i id="searchIcon" class="fas fa-search fa-2x">&nbsp;&nbsp;</i>
  <div style="display:none" class="input-group date" id="searchDate" data-target-input="nearest">
    <input type="text" class="form-control datetimepicker-input" id="datetimepicker6" data-toggle="datetimepicker" data-target="#datetimepicker6" />&nbsp;&nbsp;
    <button class="btn btn-outline-info my-2 my-sm-0" type="submit">Search</button>
  </div>
  <a style="color: black" href="logout.php"><i class="fas fa-sign-out-alt fa-2x"></i></a>
</form>

答案 1 :(得分:0)

我做了类似的事情,我想我可以帮忙!

function Test1() {
    var x = document.getElementById("searchDate");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
<i id="searchIcon" class="fas fa-search fa-2x" onclick="Test1()">

答案 2 :(得分:0)

尝试一下:

$('#searchIcon').click(function(){
    $('#searchDate').animate({
         hide: 'toggle'
    }, 1000);
}