2014-03-13 34 views
0

我想實現頁面平滑滾動和重點textarea的

<a href="#comment-textarea" id="comment-click">Comment</a> 

,單擊時,滾動到頁面底部,那裏的形式是頂部的鏈接。除了順利滾動表單外,它還關注該textarea。

現在我用這個爲smooth scrolling

爲了集中textarea,我使用了這個。

$("#comment-click").click(function() { 
    $("#comment-textarea").focus(); 
}); 

這是基本的,我知道。這工作,它順利,但它的錯誤。點擊時,屏幕會閃爍。我認爲發生的事情是當我點擊鏈接時,它直接進入頁面的底部,textarea將其聚焦,然後,在幾毫秒內,它從頁面頂部開始平滑滾動。我怎樣才能解決這個問題??

回答

0

您可以修復它通過刪除上面顯示的點擊功能並在平滑滾動中添加oncomplete功能l動畫:

$(function() { 
    $('a[href*=#]:not([href=#])').click(function() { 
     if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { 

      var target = $(this.hash); 
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); 
      if (target.length) { 
       $('html,body').animate({ 
        scrollTop: target.offset().top 
       }, 1000, function(){ // function to focus here 
        $("#comment-textarea").focus(); 
       }); 
       return false; 
      } 
     } 
    }); 
}); 
+0

謝謝你做到了。 –

+0

這將爲所有書籤關注'#comment-textarea',而不僅僅是comment-textarea。 – Fenton

+0

@SteveFenton是正確的。但考慮到這個問題的參數,它應該A)就足夠了,並且B)讓Justin成爲未來發展的一個很好的起點。 – Frankenscarf

0

您正在通過焦點調用讓書籤平滑滾動。

您確實想在動畫完成後調用焦點。 hacky的方法是在超時後運行它,但是真的應該調整順暢的滾動腳本以接受在動畫完成後運行的回調。

哈克......使用 「動畫完成」 回調

$("#comment-click").click(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
     if (target.length) { 
     $('html,body').animate({ 
      scrollTop: target.offset().top 
      }, 1000, function() { 
      $("#comment-textarea").focus(); 
     }); 
     return false; 
     } 
    } 
    } 
}); 
+0

感謝您的快速回復@steve。這肯定是有道理的 –

+0

@Frankenscarf實際上它不會,因爲它只綁定到'#comment-click'。 – Fenton

1

儘量集中你的textarea完成後滾動的

$("#comment-click").click(function() { 
    window.setTimeout(function() { 
     $("#comment-textarea").focus(); 
    }, 1000); 
}); 

例子:

$(function() { 
    $('a[href*=#]:not([href=#])').click(function() { 
     if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { 
      var target = $(this.hash); 
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); 
      if (target.length) { 
       $('html,body').animate({ 
        scrollTop: target.offset().top 
       }, 1000, function() { 
        $("#comment-textarea").focus(); 
       }); 
       return false; 
      } 
     } 
    }); 
}); 
+0

這會將'#comment-textarea'集中在頁面上的任何書籤上。 – Fenton