首页 > 解决方案 > 我的关闭按钮不适用于 jquery 动画?

问题描述

我有一个带有两个单独按钮的插件全屏搜索。一个按钮在我的网站标题中打开全屏搜索,另一个按钮用于关闭 div 内的全屏搜索。打开按钮适用于 jquery 动画,但关闭按钮不适用于 jquery 动画。

所以我想使用jquery动画幻灯片效果关闭div。

html代码:

<div id="full-screen-search">
<button type="button" class="close" id="full-screen-search-close">X</button>
</div>

动画的jQuery代码:

$("#btn_show").click(function(){
$("#full-screen-search").animate ({ width: 'show' });  
}); 

$("#full-screen-search-close").click(function(){
$("#full-screen-search").animate ({ width: 'hide' });     
});

插件的jquery代码:

     // When the document is ready...
     jQuery( document ).ready( function( $ ) {
    
// ... display the Full Screen search when:
// 1. The user focuses on a search field, or
// 2. The user clicks the Search button
$( 'form[role=search] input, form[role=search] button' ).on( 'focus, click', function( event ) {
    // Prevent the default action
    event.preventDefault();

    // Display the Full Screen Search
    $( '#full-screen-search' ).addClass( 'open' );

    // Focus on the Full Screen Search Input Field
    $( '#full-screen-search input' ).focus();
} );

// Hide the Full Screen search when the user clicks the close button
$( '#full-screen-search button.close' ).on( 'click', function( event ) {
    // Prevent the default event
    event.preventDefault();

    // Hide the Full Screen Search
    $( '#full-screen-search' ).removeClass( 'open' );
} );

 } );




   

标签: javascripthtmljquerywordpressplugins

解决方案


您不能使用show和/或hide作为宽度值。宽度必须是百分比,或带有某种单位的数字(例如300px25vw

请注意,在下面的示例中,我们在回调中显示/隐藏按钮 - 即动画完成后运行的函数。

$("#btn_show").hide();

$("#btn_show").click(function(){
  $("#full-screen-search").show().animate ({ width: '100%' }, function(){
    $("#btn_show").hide();
  });
}); 

$("#full-screen-search-close").click(function(){
  $("#full-screen-search").animate ({ width: '0px' }, function(){$("#full-screen-search").hide()}); 
  $("#btn_show").fadeIn();
});
*{position:relative;box-sizing:border-box;}
#full-screen-search{width:100%;height:80px;background:wheat;border:1px solid orange;}
#full-screen-search-close{position:absolute;top:1px;right:1px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button" id="btn_show">click</button>
<div id="full-screen-search">
  <button type="button" class="close" id="full-screen-search-close">X</button>
</div>


推荐阅读