0

我正在使用以下脚本滚动到博客中的评论部分,如果不存在评论部分,则滚动到“响应”,这是一个空的评论框:

jQuery(document).ready(function(){
    // Set up the onClick() event
    jQuery('.comments-link').click(scrollToComments);

    // If the page is page.php#comments scroll to the comments/response
    if (location.hash=='#comments') scrollToComments();
});

// This function handles the scrolling on page load and onclick
function scrollToComments(){
    var comments = jQuery('#comments');
    // this can be moved outside the function, or recalculate in case the page redraws
    var scrollTopPosition = (comments.length==0)? 
       jQuery('#respond').offset().top :
       comments.offset().top;
    jQuery('html, body').animate({scrollTop:scrollTopPosition}, 2000, 'swing');
    return false;
}

我现在还想自己滚动到个别评论,这些是在博客上使用 ID 结构“#comment-%”设置的,例如“#comment-22”。

是否有可能在 jquery 中以某种方式做到这一点?

4

1 回答 1

0

这些是你需要做的事情。

  1. 匹配location.hash模式而不是文本以处理单个评论结构。您可以使用正则表达式来实现这一点或一个简单的.startWith()替代方案。

  2. 重构scrollToComments()以接收选择器,而不是对其进行硬编码。

  3. 如有必要,使用Attribute Starts With Selector[name^="value"]来匹配各个注释。仅当您要将它们绑定到事件时才需要。不是真的需要。

于 2012-10-27T10:11:07.797 回答