2015-05-25 115 views
1

我在我的网站上使用搜索表单(我无法更改HTML结构,因为它是由Wordpress生成的搜索表单)。 我有一个搜索图标,并且我的搜索表单被隐藏。 当鼠标输入搜索div时,我想切换我的搜索表单,搜索表单在输入文本时保持可见,当鼠标移出div时,我希望隐藏搜索表单,使用与我的Jsfiddle中相同的动画。当鼠标输入div时切换搜索输入,然后隐藏鼠标输入时的搜索输入

我找不到解决方案。这里是我的HTML,我不能改变结构,因为它是由WordPress所产生的searchform:

<div id="search"> 
<form action="http://www.mmdwc.com" id="searchform" method="get"> 
<div> 
<button type="submit" class="btn" id="searchsubmit"><i class="fa fa-search"></i></button> 
<input type="search" id="s" name="s" value="" /> 
</div> 
</form>  
</div> 

我的CSS:

body {margin-top:50px;background-color:black;text-align:right} 

#search { 
    display: inline-block; 
    border-right: 1px solid #D3D3D3; 
    margin-right: 10px; 
    vertical-align: middle; 
    padding-right: 5px; 
} 

#s { 
    border-width: medium medium 1px; 
    border-style: none none solid; 
    border-color: -moz-use-text-color -moz-use-text-color #FFF; 
    -moz-border-top-colors: none; 
    -moz-border-right-colors: none; 
    -moz-border-bottom-colors: none; 
    -moz-border-left-colors: none; 
    border-image: none; 
    background-color: #000; 
    color: #D3D3D3; 
    line-height: 12px; 
    font-style: italic; 
    margin-left: 5px; 
    margin-right: 5px; 
    display: none; 
} 

#searchsubmit { 
    background-color: transparent; 
    color: #FFF; 
    border: medium none; 
    cursor: pointer; 
    font-size: 16px; 
    margin-right: -5px; 
} 

和我的jQuery:

$("#searchsubmit").stop().one("mouseenter", function() { 
    $("#s").animate({width: 'toggle'}, 200); 
}); 

和JSfiddle在动作中看到它(带动画):

http://jsfiddle.net/7hbp57my/

有人可以帮我吗?

非常感谢您的帮助

回答

2

你不应该单独使用mouseentertoggle动画至少不会。
使用mouseenter您还必须将mouseleave事件设置为oposite操作。

您应该附加事件处理程序的元素是整个#search div,而不是按钮。

.stop()不需要,因为它不执行任何动画按钮(你宁愿停止输入场动画:$("#s").stop().animate(...))。

one仅用于执行一次事件处理程序。事件被捕获后,它立即从元素中移除,不再执行。你当然不需要这个。如果您需要event delegation,请改为使用on


// cache input element (good practice when you refer to the same object many times): 
var s_field = $("#s"); 

// hover instead of mouseenter: 
$("#search").hover(
// on mouse over: 
function() { 
    // use 'show' instead of toggle: 
    s_field.stop().animate({width: 'show'}, 200); 
}, 
// on mouse out: 
function(){ 
    // hide input field on "hover out" only when it has no focus: 
    if(!s_field.is(":focus")){ 
     s_field.stop().animate({width: 'hide'}, 200); 
    } 
}); 

Optionaly,你可以隐藏搜索元素(并清除其)通过结合focusout事件处理程序,重点是从现场移除,:

s_field.focusout(function(){ 
    // check if mouse pointer is over the element 
    // otherwise search field will disapear before button is clicked 
    if(!$("#search").is(":hover")){ 
     s_field.val('').animate({width: 'hide'}, 200); 
    } 
}); 

JSFiddle


为了更好地掌握rstand jQuery的.hover()处理器(简写为等效和mouseentermouseleave):

$(element).hover(handlerIn, handlerOut); 

其他参考:

+0

感谢您的帮助,现在我更好地了解如何做到这一点!非常感谢,它完美地工作 – mmdwc

+0

很高兴我可以帮助:-)有一个改进版本:[JSFiddle](http://jsfiddle.net/t1qxpq6t/)。我在'focusout'处理程序中添加了'.is(':hover')''条件。否则按钮点击不起作用 –