如果元素太高,則觸發的代碼段很有效,假設frame元素和它的子元素相對定位。如果不是,它使用絕對偏移量,它不起作用。
至於如果元素太低會觸發的部分,我假設當您說「它總是傾向於滾動一點點通過目標元素而不是直到它的最後」時,您指的是事實上,如果框架小於其偏移量,則元素被切斷。請嘗試以下操作:
// If the frame is less than or equal to the element's height
if(frameHeight <= elem.attr('height')){
//Scroll to it's offsetBottom - the total frameHeight, so that the full element will be displayed
frame.scrollTop(offsetBottom - frameHeight);
}else {
//Else, the element's height is less than the frame, so the entire element will be displayed if we just scroll to the element's offsetBottom.
frame.scrollTop(offsetBottom);
}
我創建了一個HTML演示頁面,如下所示,沒有遇到任何其他問題。玩弄元素的高度,看看你是否能把它打破。我使用Firefox 3.5,一切都很酷。
<button id="buttonTest1">Slide to Test1</button> <button id="buttonTest2">Slide to Test2</button>
<div style="position:relative;width:100%;height:620px;overflow:scroll;">
<div style="position:relative;height:50px;"></div>
<div id="childSlide1" style="width:50px;height:50px;position:relative;">Test</div>
<div id="childSlide2" style="width:50px;height:50px;position:relative;top:850px;">Test2</div>
</div>
$(document).ready(function(){
function keepScrolledOver(elem){
var frame = elem.parent();
var scrollPos = frame.scrollTop();
var offset = elem.attr("offsetTop");
alert ('scrollPos: '+scrollPos+' offset: '+offset);
//var jQoffset = elem.offset();
//alert ('jQoffset: '+jQoffset.top+' '+jQoffset.left);
// If the element is scrolled too high...
if(offset < scrollPos)
{
alert ('scrollPos '+scrollPos+' is bigger than offset '+offset);
frame.scrollTop(offset);
// frame.attr("scrollTop", offset);
}
// If the element is scrolled too low...
else
{
var frameHeight = frame.height();
var offsetBottom = offset + elem.height();
var scrollBottom = scrollPos + frameHeight;
alert('frameHeight: '+frameHeight+' offsetBottom: '+offsetBottom+' scrollBottom: '+scrollBottom);
if(offsetBottom > scrollBottom)
{
// frame.attr("scrollTop", offsetBottom);
if(frameHeight <= elem.attr('height'))
{
frame.scrollTop(offsetBottom - frameHeight);
// frame.attr("scrollTop", offsetBottom - frameHeight);
}else {
frame.scrollTop(offsetBottom);
}
}
}
}
$('#buttonTest1').click(function(){
var scrollElement = $('#childSlide1');
keepScrolledOver(scrollElement);
});
$('#buttonTest2').click(function(){
var scrollElement = $('#childSlide2');
keepScrolledOver(scrollElement);
});
});