单击外部按钮以使用切换关闭弹出窗口

时间:2014-11-14 11:02:54

标签: html css jsfiddle

我曾使用切换按钮创建搜索表单。但是我想在任何位置外面点击以关闭搜索表单,而不仅仅是使用按钮。

HTML

<a href="#" data-mini="false" data-theme="e" data-role="button" class="opensearch" data-icon="search" data-iconpos="right">Search</a>
<div class="search_field" style="display:none;">
    <form>
        <input name="search" class="search" value="" placeholder="Search Item...." type="text" data-theme="e" />
        <input type="submit" value="Search" data-mini="false" data-icon="search" data-iconpos="notext" data-theme="c" />
    </form>
</div>

Jquery:

 $(function() {
     $(".opensearch").on('click', tapHandler);
     function tapHandler(event) {
         $('.search_field').toggle();
         $('.search').focus();
     }
 });

JsFiddle

的演示

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:4)

使用模糊事件:

$(".search").on("blur",function(){
    $('.search_field').toggle();
});

更新了小提琴:JsFiddle demo


[编辑]您可能想要在隐藏字段之前检查新焦点是否在搜索图标上:

$(".search").on("blur",function(){
  setTimeout(function(){
    var target = document.activeElement;
    target = target ? target.id||target.tagName||target : '';

    if(target!="INPUT"){
        $('.search_field').toggle();
    }

  }, 1);        
});

最好使用按钮的ID ....

示例:JsFiddle demo

答案 1 :(得分:1)

您可以执行类似

的操作

 $(function() {

   $(".opensearch").on('click', tapHandler);
   //add a click handler to the document object
   $(document).on('click', function(e) {
     //if the click is happening inside the search_field or opensearch elements then don't do anything
     if ($(e.target).closest('.search_field, .opensearch').length == 0) {
       $('.search_field').hide();
     }
   });

   function tapHandler(event) {
     $('.search_field').toggle();
     $('.search').focus();
   }

 });
.search_field {
  padding: 10px 10px 0;
  position: relative;
}
.search_field .ui-submit {
  bottom: -2px;
  position: absolute;
  right: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" data-mini="false" data-theme="e" data-role="button" class="opensearch" data-icon="search" data-iconpos="right">Search</a>

<div class="search_field" style="display:none;">
  <form>
    <input name="search" class="search" value="" placeholder="Search Item...." type="text" data-theme="e" />
    <input type="submit" value="Search" data-mini="false" data-icon="search" data-iconpos="notext" data-theme="c" />
  </form>
</div>