jQuery扩展搜索图标输入,工作不正常

时间:2016-02-23 22:23:21

标签: javascript jquery html css twitter-bootstrap

我有这个搜索框,我到目前为止已经完成但是对JS来说是新手,所以有点卡住了。

我需要它向右滑动以显示它背后的输入,当我只使用按钮时它确实有效但我猜我只需要添加图标所以当你点击它但没有提交但是滑过但是然后我猜还需要在输入中输入内容时显示按钮并隐藏图标,如果没有,则单击图标时会再次关闭。

有点像这样我想...... http://codepen.io/nikhil/pen/qcyGF - 这就是我一直想要的基础。

searchExpand = function(elm){
  var spanIcon = $('.span-icon'),
  searchInput = $('.search-input'),
  searchForm = $('.search-form'),
  btnSearch = $('.btn-search'),
  isOpen = false;

  if(isOpen == false){
    searchForm.addClass('open');
    spanIcon.hide();
    btnSearch.show();
    searchInput.focus();
    isOpen = true;
  } else {
    searchForm.removeClass('open');
    btnSearch.hide();
    spanIcon.show();
    searchInput.focusout();
    isOpen = false;
  }
}

$(document).ready(function(){
  
  // lets make the search feature happen!
  $(document).on("click", "span.btn-search", function() {
    searchExpand(this);
  });

});
.search-form {
  width: 0%;
}

.search-form input {
  border-right-style: none;
}

.search-form button {
  background: none;
  padding: 0;
  display: none;
}

.search-form button i {
  font-size: 1.9em;
  color: #000;
  padding: 10px;
}

.search-form span.search-icon {
  font-size: 1.9em;
  color: #000;
  padding: 10px;
  cursor: pointer;
}

.search-form .form-control {
  padding: 0;
  border: 0;
}

.search-form .input-group-addon {
  background: #fff;
  border: 0;
}

.search-form.open {
  width: 100%;
}

.search-form.open .form-control {
  padding: 30px 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<form role="search" class="search-form">
  <div class="input-group add-on">
    <input type="text" class="form-control search-input" placeholder="Enter a search term" name="search" id="search">
    <div class="input-group-addon">
      <button class="btn btn-clear btn-search" type="submit"><i class="glyphicon glyphicon-search search-icon"></i></button>
      <span class="span-icon glyphicon glyphicon-search search-icon"></span>
    </div>
  </div>
</form>

1 个答案:

答案 0 :(得分:1)

请注意,您的.btn-search不在span中,因此您的函数searchExpand将不会运行。当您单击按钮时。

跨度中的是“span-icon glyphicion ....”

如果您正在使用jquery,这将是实现您想要的有效方式:

为跨度调用ID分配ID,并更改您的js以反映:

 $( "#yourbuttonidname" ).click(function() {
    searchExpand(this);
  });

新范围的示例:

<span id="yourbuttonidname" class="span-icon glyphicon glyphicon-search search-icon"></span>