使用jQuery slideDown或toggleClass和CSS过渡添加向下滑动效果

时间:2018-10-05 13:57:13

标签: jquery html css

我有一个简单的真正的标题,在其中放置了搜索栏。搜索栏占据整个宽度。我想在jquery中添加slidetoggle效果,以使其上下滚动:

HTML:

<body>
    <header>
        <div class="search-bar">
            <form action="/action_page.php">
                <input type="search" name="q" placeholder="Search">
            </form>
        </div>

        <div id="top-nav" class="container-fluid">
            <div class="top-nav-wrapper">
                <a class="top-req-info" href="#" >Request Info</a>
                <ul class="top-nav-right">
                    <li class="hidden search-icon"><img src="images/search.png"></li>
                </ul>
            </div>
        </div>
    </header>
</body>

CSS:

    .search-bar input {
        background-color: #821A31;
        color: #ffff;
        font-size: 35px;
        border: 0;
        margin: 0;
        height: 76px;
        width: 100%;
        padding: 0 80px;
        font-weight: 200;
        display: none;
    }
    .search-bar input:focus, .search-bar input:focus{
        outline: none;
    }
    .search-bar input.slide-down {
        display: block;
    }
    .search-bar input::placeholder {
        color: white;
    }
    .hover-bar {
        background: #821A31!important;
    }

jQuery:

    $('.search-icon').click(function() {
        $('.search-bar input').toggleClass('slide-down');
        $('#top-nav-book, .top-req-info').toggleClass('hover-bar');
    });

问题是,如果我使用slideToggle而不是toggleClass,它将不起作用,因为它将给我一个错误,并且如果我使用例如高度或可见性之间的过渡,则不会发生任何事情。我只需要在无显示和显示块之间创建一个令人愉悦的动画,以创建一种下拉式滑动效果。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

slideToggle()是用于处理整个动画的jQuery方法。 options here的完整列表。

$('#top-nav').on('click','.search-icon',function() {
  $('input','.search-bar').slideToggle();
});

看到它正常工作:

$('#top-nav').on('click','.search-icon',function() {
  $('input','.search-bar').slideToggle();
});
.search-bar input {
  background-color: #821A31;
  color: #ffff;
  font-size: 35px;
  border: 0;
  margin: 0;
  height: 76px;
  width: 100%;
  padding: 0 80px;
  font-weight: 200;
  display: none;
}

.search-bar input:focus,
.search-bar input:focus {
  outline: none;
}

.search-bar input::placeholder {
  color: white;
}

.hover-bar {
  background: #821A31;
}
.top-nav-right {
  list-style-type: none;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
  <div class="search-bar">
    <form action="/action_page.php">
      <input type="search" name="q" placeholder="Search">
    </form>
  </div>

  <div id="top-nav" class="container-fluid">
    <div class="top-nav-wrapper">
      <ul class="top-nav-right">
        <li class="hidden search-icon"><i class="fa fa-search"></i></li>
      </ul>
    </div>
  </div>
</header>