3

我正在将jQuery 扩展器用于阅读更多阅读更少类型的情况,它工作正常。我想在用户点击阅读少后滚动到文章的标题。我试图弄清楚代码,但我对 jQuery 不太熟悉。

$('.expand_please').expander({
  slicePoint: 1000,
  widow: 2,
  expandEffect: 'show',
  userCollapseText: 'Read less',
  expandText: 'Read more',
  onCollapse: $(this).closest('h2').scroll()
});

编辑:相关HTML:

<div class="row keyline" id="show_article1">
  <h2 style="margin-bottom: 1em;">TITLE</h2>
  <div class="link_article" style="display: none;"><a href="/share/thomas/more/18" data-remote="true">READ MORE</a></div>
  <div class="fivecol">
    <img alt="thumbnail" class="thumbnail" src="/system/thumb.jpg">
  </div>
  <div class="sevencol last expand_please marginer"><div class="summary" style="display: none;">
  ARTICLE BODY TEXT
  <span class="read-less"><a href="#">Read less</a></span>
  </div>
</div>
4

2 回答 2

3

To scroll to the element in question, you simply need to get its offset().top value, and pass that value to the animate() method.

It'd look something like this:

$('.expand_please').expander({
      slicePoint: 1000,
      widow: 2,
      expandEffect: 'show',
      userCollapseText: 'Read less',
      expandText: 'Read more',
      onCollapse: function(){
        var amount = $(this).siblings('h2:first').offset().top;
        $('body, html').animate({scrollTop : amount},800);

      }
});

The above method will obviously animate the scroll, which is a nice touch, but should you just want something more basic, you can use element.scrollIntoView(true);1

In your case, that would be:

...
onCollapse: function(){
    // pass true to align with top of scroll area
    // pass false to align with bottom of scroll area
    $(this).siblings('h2:first').scrollIntoView(true)
}
...

1 https://developer.mozilla.org/en-US/docs/DOM/element.scrollIntoView

于 2013-04-11T03:43:48.477 回答
2

我相信 onCollapse 想要一个函数在展开器折叠时调用。您也在寻找 jQuery 的 .scrollTop 方法而不是 .scroll。.scroll 将处理程序附加到滚动事件。尝试以下

$('.expand_please').expander({
    slicePoint: 1000,
    widow: 2,
    expandEffect: 'show',
    userCollapseText: 'Read less',
    expandText: 'Read more',
    onCollapse: function () {
        $('body').scrollTop($(this).closest('h2').offset().top);
    }
});

更新: .closest() 将不起作用,因为它会查看匹配元素集的祖先。在提供的 HTML 中,您实际上是在尝试选择同级,例如

$(this).siblings('h2').first().offset().top
于 2013-04-11T03:38:26.330 回答