2017-05-08 57 views
0

首先,先謝謝你支持我的問題。jQuery,WordPress - 點擊按鈕ID顯示邊欄,但也滾動到它

我相信結果將是直截了當的;但我有一個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? 
}); 
}); 

EDITE d 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 
}); 
}); 

回答

0

我已經創造了它應該如何工作笑着例子。希望這將 幫到您:)

$(function() { 
 
    $("#sidebar-toggle").on("click", function() { //Click 
 
\t $("#sidebar").slideToggle("slow", function(){ 
 
\t \t \t if ($(this).is(":visible")) { //Check to see if element is visible then scroll to it 
 
\t \t \t \t $('html,body').animate({ //animate the scroll 
 
\t \t \t \t \t scrollTop: $(this).offset().top 
 
\t \t \t \t }, "slow") 
 
\t \t \t } 
 
\t \t }); 
 
\t return false; //This works similarly to event.preventDefault(); as it stops the default link behavior 
 
\t }); 
 
});
.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 e.g. text is here 
 
</div> 
 
</div>

要只檢查是否聲明:

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") 
       } 
)}; 
+0

大@Sahil Dhir!但是,當點擊此按鈕時,我正在使用的WordPress主題已經控制了側邊欄的這種可見性。所以,我希望只是爲了使scrollTop工作,所以它直接進入側邊欄div。有什麼想法嗎? – MichaelMHL

+0

我們可以更改jQuery,以便檢查#邊欄是否已經出現(由WordPress主題控制),然後根據您的指示完成剩下的工作? – MichaelMHL

+0

然後只是調用if語句,不使用代碼的其餘部分..如果條件將檢查側欄是否可見,它將滾動到..檢查更新的答案 –