簡體   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