簡體   English   中英

jQuery:slideToggle,然后滾動到div

[英]Jquery: slideToggle, then scroll to div

單擊導航按鈕時,我正在使用slideToggle顯示div 它正在工作,但是我要顯示的div很高,因此一旦加載,您實際上看不到太多。 div直接位於用於觸發slideToggle的按鈕下方。 我想找到一種方法來slideToggle div ,然后將窗口滾動到導航按鈕,自動顯示整個先前隱藏的div

<a href="#">不起作用,因為它試圖在slideToggle函數執行之前跳到該元素。 slideToggle完成之后,有沒有辦法讓窗口滾動到該元素?

你可以看到我到目前為止在這里

單擊printables按鈕以查看我在說什么。

我還創建了基本功能jsfiddle的jsFiddle

$('a').click(function(event){
    event.preventDefault();

    $(element).slideToggle(250, function(){
        window.location.hash = "#content";
    });
});

應該管用。

Robert帶羅伯特的答案,您可以通過不使用哈希來對其進行清理。

$('a').click(function(event){
    event.preventDefault();
    $a = $(this);

    $(element).slideToggle(250, function(){
        $(window).scrollTop($a.offset().top);
    });
});

乍得和羅伯特提供的兩個答案都是有效的,但是,我想寫的有點不同。

以下是基於您的jsFiddle的示例。 JS是您需要的部分。

 $(function() { $( "#button" ).on( "click", function() { //Click $( "#content" ).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 - 25 // the - 25 is to stop the scroll 25px above the element }, "slow") } }); return false; //This works similarly to event.preventDefault(); as it stops the default link behavior }); }); 
 /* This is for the example */ #button{ display: block; margin: auto; margin-top:130px; height: 50px; width: 180px; background-color: #ccc; } #content{ display: none; margin: 0 auto; height: 1200px; width: 170px; background-color: blue; } 
 <!-- HTML for example --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" id="button">Click to expand content</a> <div id="content"> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM