0

我在我的网站上使用以下 jquery 脚本在博客条目页面上从顶部的评论链接向下滚动到底部的实际评论:

   jQuery(document).ready(function(){      
       var TopPosition = jQuery('#comments').offset().top;     
       jQuery('.comments-link').click(function(){        
           jQuery('html, body').animate({scrollTop:TopPosition}, 2000, 'swing');
           return false;
       });   
   });

当'#comments'不存在时,我还希望页面向下滚动到“#respond”。这是否可能在jquery中使用if/else/and?

此外,是否可以从带有评论链接的不同页面(即我的博客的索引页面)链接到单个博客条目的评论,并且还可以向下滚动动画?

希望这是有道理的。

4

1 回答 1

3

如果您想滚动到#respond何时#comments不存在,只需检查选择器返回的对象的长度......如果它是 0 则它不在页面上,您可以使用offset().topof#respond代替。

jQuery(document).ready(function(){
   var comments = jQuery('#comments');
   var TopPosition = (comments.length==0)? 
       jQuery('#respond').offset().top :
       comments.offset().top;     
   jQuery('.comments-link').click(function(){        
       jQuery('html, body').animate({scrollTop:TopPosition}, 2000, 'swing');
       return false;
   });   
});

要在页面加载时向下滚动,您需要使用哈希(例如page.php#comments),但是传统上您将有一个锚标记 ( <a name="comments'></a>),并且页面会跳转到它。如果你想有一个流畅的滚动,你可以看看location.hash然后触发滚动。由于它实际上与onClick我将其分解为一个您可以同时调用两者的函数相同:

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;
}
于 2012-10-19T14:41:21.013 回答