2014-09-21 48 views
0

我想在页面右上方制作一个像http://www.chess24.com/这样的小搜索框。如何用Jquery正确找到焦点?

这是我的HTML和平:

<div class="input-group" id="searchBox"> 
    <input name="data[Search]" class="form-control" id="searchText" style="display : none; width : 0;" type="text"/> 
    <button class="btn btn-default" type="button" id="searchBtn">Go!</button> 
</div> 

和jQuery代码是:

$(document).ready(function() { 
    $('#searchBtn').on('mouseenter',function(){ 
     $('#searchText').show(); 
     $('#searchText').animate({width: '200px'}, 500, function() {$('#searchText').focus(); 
     }); 
    }); 
    $('#searchText').blur(function() { 
     if (!($('#searchBtn').is(":active")) && !($('#searchText').is(":active"))) 
      $('#searchText').animate({width: '0'}, 500, function() {$(this).hide();}); 
     console.log($(document.activeElement)); 
    }); 


}); 

问题是,当焦点将按钮或点击按钮文本框将关闭。 我想关闭它,指出这两个元素。

回答

1
$(document).on('click', function(event) { 
    var idx = event.target.id; 
    //if clicked element is not searchText or searchbtn, but searchtext is visible 
    if (idx !== 'searchText' && idx !== 'searchBtn' && $('#searchText').is(":visible")){ 
    $('#searchText').animate({width: '0'}, 500, function() {$(this).hide();}); 
    } 
}); 

有几种方法可以解决这个问题。只是一个提示。

+0

谢谢,这太有用 – 2014-09-21 17:49:23

+1

而不是事件应该是e.target – 2014-09-21 17:49:42

+2

而'event.target.id',jQuery只是让这个过程更加昂贵。 – 2014-09-21 18:31:08