jQuery滚动到ID元素的底部

问题描述:

我想要一个按钮,将页面滚动到给定元素id。我现在有这个Fiddle,但我想它有些不同:jQuery滚动到ID元素的底部

  1. 滚动,直到蓝格(#three)的底部是在页面的底部,而不是DIV滚动到页面顶部的顶部。
  2. 只有当元素在屏幕上对用户不可见时才滚动。

这怎么办?

HTML

<button id="btn">CLICK</button> 
<div class="test" id="one"></div> 
<div class="test" id="two"></div> 
<div class="test" id="three"></div> 
<div class="test" id="four"></div> 

CSS

.test { 
    width: 100%; 
    height: 400px; 
} 

#one { background: red; } 

#two { background: green; } 

#three { background: blue; } 

#four { background: yellow; } 

JS

$("#btn").click(function() { 
    $('html, body').animate({ 
     scrollTop: $("#three").offset().top 
    }, 500); 
}); 
+0

理解了第一个,我有一个解决方案,但没有理解>“只有当元素在屏幕上对用户不可见时才滚动。“ – divy3993

+0

如果你已经可以看到这个元素 - 那么不要做动画 – Chris

好这里是第一部分 -

$('html, body').animate({ 
    scrollTop: ($("#three").offset().top + $("#three").height() - $(window).height()) 
}, 500); 

数学的只是一点点,你可以很容易地通过自己明白这是怎么回事。

和用于第二部分 -

if(($('#three').offset().top >= $(window).scrollTop()) && ($('#three').offset().top < $(window).scrollTop() + $(window).height())) { ... 
} 

值的复杂的比较,来检查的可视性,如果顶部元件的偏移量是在窗口scrollTop的(之间)和+窗口高度()(即像偏移底部的窗口)。

退房的fiddle

UPDATE:有一个在以前的一个错误,你需要一个额外的条件语句考虑底部(窗口scrollTop的之间的元素的偏移检查#three的可见性)和窗口的底部偏移量。所以全部条件将变成 -

var eloffbottom = $('#three').offset().top + $('#three').height(); 
var winoffbottom = $(window).scrollTop() + $(window).height(); 
if((($('#three').offset().top >= $(window).scrollTop()) && ($('#three').offset().top < winoffbottom)) || ((eloffbottom >= $(window).scrollTop()) && (eloffbottom < winoffbottom))) { 
       alert('already in view'); 
    } 

UPDATED Fiddle完全可以工作!

顺便说一句,刚刚找到一个jQuery的插件可以为你做到这一点。 See here。只需使用它作为 - $('#three').visible() - 返回true或false。

+0

只适用于'如果元素在屏幕上对用户是不可见的.' +1 – Tushar

+0

我已经upvoted for实施:)其他答案不包括我的 – Tushar

减去计算顶部从元素偏移顶部开始的窗口高度,然后添加元素高度。

Demo

$("#btn").click(function() { 
 
    var winHeight = $(window).height(), 
 
    topOffset = $("#three").offset().top, 
 
    elementHeight = $('#three').height() 
 
    var top = topOffset - winHeight + elementHeight; 
 

 
    $('html, body').animate({ 
 
    scrollTop: top 
 
    }, 500); 
 
});
.test { 
 
    width: 100%; 
 
    height: 400px; 
 
} 
 
#one { 
 
    background: red; 
 
} 
 
#two { 
 
    background: green; 
 
} 
 
#three { 
 
    background: blue; 
 
    border: solid 3px gray; 
 
} 
 
#four { 
 
    background: yellow; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 
<button id="btn">CLICK</button> 
 
<div class="test" id="one"></div> 
 
<div class="test" id="two"></div> 
 
<div class="test" id="three"></div> 
 
<div class="test" id="four"></div>

+0

不错的解决方案@Tushar –