簡體   English   中英

平滑滾動和聚焦文本區域

[英]Smooth scroll and focus textarea

我想要一個指向頁面頂部的鏈接

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

單擊時滾動到頁面底部(窗體所在的位置)。 除了平滑滾動到表單外,它還會聚焦該文本區域。

現在,我正在使用它進行平滑滾動

為了使文本區域集中,我正在使用它。

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

我知道這很基本。 這可以工作,並且可以平滑,但是有很多問題。 單擊后,屏幕會閃爍。 我認為正在發生的事情是,當我單擊鏈接時,它會直接到達文本區域要聚焦的頁面底部,然后在幾毫秒內從頁面頂部開始平滑滾動。 我怎樣才能解決這個問題??

完成滾動后,嘗試將textarea聚焦:

$(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;
            }
        }
    });
});

您正在通過焦點通話來加速滾動到書簽。

您真的想在動畫完成后調用焦點。 hacky的方法是在超時后運行它,但實際上您應該調整平滑滾動腳本以接受將在動畫完成后運行的回調。

哈克...

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

使用“動畫完成”回調的示例

$("#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;
      }
    }
  }
});

您可以通過刪除上面顯示的click函數並向平滑滾動動畫添加oncomplete函數來解決此問題:

$(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;
            }
        }
    });
});

暫無
暫無

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

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