繁体   English   中英

jQuery,WordPress-单击按钮ID以显示边栏,但也滚动到它

[英]jQuery, WordPress - Click button id to show sidebar but also scroll to it

首先,首先感谢您支持我的问题。

我相信结果将是直截了当的。 但我有一个ID为“ sidebar-toggle ”的WordPress按钮,它用css表示为图标。 单击此按钮时,将显示一个侧边栏,再次单击(关闭)侧边栏将隐藏。

但是,这是我的index.php页面,其中显示最新帖子。 因此,当出现侧边栏时,它会一直显示在页面的最下方,位于最新帖子的下方。

当单击按钮时,如何最好地利用jQuery成功向下滚动到侧栏div?

CSS

<button id="sidebar-toggle" class="sidebar-toggle"></button>

HTML

<div id="sidebar" class="sidebar"> 
<div id="sidebar-inner" class="sidebar-inner">
// all inner content e.g. text is here
</div>
</div>

jQuery的

jQuery(document).ready(function() {
jQuery("#sidebar-toggle").live("click", function(event){
jQuery('html,body').animate({ scrollTop:$('#sidebar').offset().top});
// the sidebar doesn't appear until clicked - problem when scrolling?
});
});

编辑的查询

        jQuery(function() {
   jQuery("#sidebar-toggle").on( "click", function() { //Click

        if (jQuery("#sidebar").is(":visible")) { //Check to see if element is visible then scroll to it
            jQuery('html,body').animate({ //animate the scroll
                scrollTop: $('#sidebar').offset().top 
            }, "slow")
        }
    });
  return false; //This works similarly to event.preventDefault(); as it stops the default link behavior
});
});

我已经创建了一个有关如何工作的简单示例。 希望它能对您有所帮助:)

 $(function() { $( "#sidebar-toggle" ).on( "click", function() { //Click $( "#sidebar" ).slideToggle( "slow", function(){ if ($(this).is(":visible")) { //Check to see if element is visible then scroll to it $('html,body').animate({ //animate the scroll scrollTop: $(this).offset().top }, "slow") } }); return false; //This works similarly to event.preventDefault(); as it stops the default link behavior }); }); 
 .sidebar{ margin-top:500px; height:500px; width:200px; background:red;display:none} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="sidebar-toggle" class="sidebar-toggle">toggler</button> <div id="sidebar" class="sidebar"> <div id="sidebar-inner" class="sidebar-inner"> // all inner content eg text is here </div> </div> 

仅检查if语句:

   jQuery(function() {
    if (jQuery('#sidebar').is(":visible")) { //Check to see if element is visible then scroll to it
                    jQuery('html,body').animate({ //animate the scroll
                        scrollTop: jQuery('#sidebar').offset().top 
                    }, "slow")
                }
)};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM