jQuery scrolltop if / else /和来自不同的页面?

时间:2012-10-19 14:37:20

标签: jquery

我在我的网站上使用以下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 /和?

此外,是否可以将不同的页面与评论链接(即我的博客的索引页面)链接到各个博客条目的评论,还可以将动画向下滚动?

希望这是有道理的。

1 个答案:

答案 0 :(得分:3)

如果你想在#respond不存在的情况下滚动到#comments,只需检查选择器返回的对象的长度......如果它是0,那么它不在页面上,并且您可以使用offset().top代替#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;
}