[英]jQuery, WordPress - Click button id to show sidebar but also scroll to it
Firstly, thank you in advance for supporting my question. 首先,首先感谢您支持我的问题。
I believe the outcome will be straight-forward; 我相信结果将是直截了当的。 but I have a WordPress button with id " sidebar-toggle " and its represented as an icon with css.
但我有一个ID为“ sidebar-toggle ”的WordPress按钮,它用css表示为图标。 When this button is clicked, a sidebar appears, and when clicked again (to close) the sidebar hides.
单击此按钮时,将显示一个侧边栏,再次单击(关闭)侧边栏将隐藏。
However, this is my index.php page which shows latest posts. 但是,这是我的index.php页面,其中显示最新帖子。 So when the sidebar appears, it appears all the way down the page, underneath the latest posts.
因此,当出现侧边栏时,它会一直显示在页面的最下方,位于最新帖子的下方。
How would you best ultilise jQuery to successfully scroll down to the sidebar div when the button is clicked? 当单击按钮时,如何最好地利用jQuery成功向下滚动到侧栏div?
CSS CSS
<button id="sidebar-toggle" class="sidebar-toggle"></button>
HTML 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的
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?
});
});
EDITED JQUERY 编辑的查询
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
});
});
I have created a simle example of how it should work.
我已经创建了一个有关如何工作的简单示例。 Hope it will help you :)
希望它能对您有所帮助:)
$(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>
To check only if statement: 仅检查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.