繁体   English   中英

用户单击“阅读更多”链接后,停止页面滚动到顶部

[英]Stop page scrolling to the top after the user clicks a read more link

html页面上使用以下功能来显示/隐藏有关注释的更多详细信息。 问题是,当单击“阅读更多”链接时,页面总是向上滚动到顶部,因此使用户脱离了他们尝试查看的实际评论。

尝试使用return false;是否正确return false; 在下面的代码块中? 如果是这样,在哪里?

var collapseIt = function(){

     var collapsedSize = '25px';
   $('.item').each(function() {

    var h = this.scrollHeight;

    console.log(h);
    var div = $(this);

    if (h > 40) {
      div.css('height', collapsedSize);
      div.after('<a id="more" class="item" href="#">Read more</a><br/>');
      var link = div.next();
      link.click(function(e) {
        e.stopPropagation();

        if (link.text() != 'Collapse') {
          link.text('Collapse');
          div.animate({
            'height': h
          });

        } else {
          div.animate({
            'height': collapsedSize
          });
          link.text('Read more');
        }

      });
    }

  });   
};

最简单的方法是阻止默认操作:

link.click(function(e) {
  e.preventDefault();
});

另一种方法是返回到滚动位置:

var scrollTop = document.body.scrollTop;

link.click(function(e) {
  document.body.scrollTop = scrollTop;
});

用下面的代码行替换添加“阅读更多”链接的代码:

div.after('<a id="more" class="item" href="#!">Read more</a><br/>');

这个答案在这里得到了很好的解释:

https://stackoverflow.com/a/11246131/802651

e.preventDefault()

在点击处理程序的开头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM