使用jquery切换来更改按钮图标

时间:2015-03-26 14:24:41

标签: jquery html css

我正在使用这样的jquery切换命令:

http://jsfiddle.net/hbz9oa34/

$(".searchbtn").click(function () {
    $("#search").toggle();
});

切换菜单打开菜单后,将搜索图标更改为关闭图标的最佳方式是什么?

3 个答案:

答案 0 :(得分:1)

这样的事情我对你的html css和jquery Fiddle进行了一些修改



$('a').click(function(){
   $(this).toggleClass('close')
})

* {
    margin: 0;
    padding: 0;
}
.input {
    width:100%;
    display: block;
    margin-bottom: 10px;
    background-color: transparent;
}
.header {
    display: block;
    border-bottom: 1px solid #e5e5e5;
    padding: 10px 20px;
}
.nav {
    background-color: white;
    padding: 10px 20px;
}
#search {
    display: none;
    padding-top: 10px;
}
.searchbtn{
    display:block;
    width:50px;
    height:50px;
}
.menu-open{
    background:url('https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSaDYCb1sQ4jBwqwAhvjuupepjUw2PTrzJAnFXxA7Q3VsrCHit_Af75fR0');
     background-size:100% 100%;
}

.close{
    background:url('http://www.wpclipart.com/computer/icons/close_button_red.png');
    background-size:100% 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
    <div class="header">
<a href="index.html"><img src="./img/logo.svg"></a>

<a  class="searchbtn menu-open" ></a>

        <form id="search">
            <input type="text" class="input" id="keyword" placeholder="Keyword">
        </form>
    </div>
    <div class="nav">test</div>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用CSS代替img代码来使其更通用。

CSS:

.icon-search {
  background: url("/img/search.svg");
  width: 30px;
  height: 30px;

}

 // update the width and height as required.

.icon-close {
  background: url("/img/close.svg");
  width: 30px;
  height: 30px;
}

JS:

$(".searchbtn").click(function () {
     $(this).find("i").toggleClass("icon-search icon-close")
});

HTML:

  <a href="#" class="searchbtn"><i class="icon-search"></i></a>

答案 2 :(得分:1)

http://jsfiddle.net/hbz9oa34/3/

您可以为搜索按钮和搜索表单添加包装器:

<div class="header__search">
  ...
</div>

然后,在单击搜索按钮时,您可以向该包装器添加类以指示搜索已打开:

$('.header__search').addClass('header__search--opened');

现在您可以使用css更改图标。

然后,点击关闭按钮,您可以删除以前添加的课程:

$('.header__search').removeClass('header__search--opened');
相关问题