繁体   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