Javascript jQuery建议:如何改进将元素滚动到视图中的功能?
我创建了一个函数,可以将给定的子元素滚动到其父元素中的视图中。内容如下:Javascript jQuery建议:如何改进将元素滚动到视图中的功能?,javascript,jquery,firefox,refactoring,scroll,Javascript,Jquery,Firefox,Refactoring,Scroll,我创建了一个函数,可以将给定的子元素滚动到其父元素中的视图中。内容如下: function keepScrolledOver( elem ) { frame = elem.parent(); var scrollPos = frame.scrollTop(); var offset = elem.attr( "offsetTop" ); // If the element is scrolled too high... if( offset <
function keepScrolledOver( elem )
{
frame = elem.parent();
var scrollPos = frame.scrollTop();
var offset = elem.attr( "offsetTop" );
// If the element is scrolled too high...
if( offset < scrollPos )
{
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;
if( offsetBottom > scrollBottom )
{
// frame.attr( "scrollTop", offsetBottom );
if( frameHeight < offsetBottom )
frame.scrollTop( offsetBottom - frameHeight );
// frame.attr( "scrollTop", offsetBottom - frameHeight );
}
}
}
函数keepScrolledOver(elem)
{
frame=elem.parent();
var scrollPos=frame.scrollTop();
var offset=要素属性(“offsetTop”);
//如果元素滚动得太高。。。
如果(偏移量<滚动位置)
{
帧。滚动顶部(偏移);
//frame.attr(“滚动顶部”,偏移量);
}
//如果元素滚动得太低。。。
其他的
{
var frameHeight=frame.height();
var offsetBottom=偏移量+元素高度();
var scrollBottom=scrollPos+帧高;
如果(偏移底部>滚动底部)
{
//frame.attr(“滚动顶部”,偏移底部);
如果(帧高度<偏移底部)
frame.scrollTop(偏移底部-帧高度);
//frame.attr(“scrollTop”,offsetBottom-frameHeight);
}
}
}
到目前为止,对于我的Firefox web应用程序(我的意思是,到目前为止,我只在Firefox上进行了测试),这非常有效。唯一的问题是,对于滚动得太低的元素,它总是倾向于滚动到目标元素的一小部分,而不是一直滚动到它的末尾。我不确定元素填充是否和我的数学很差有关
有人对如何改进这一点有什么高明的想法吗?假设框架元素及其子元素处于相对位置,那么在元素过高时激发的代码部分工作得很好。如果不是,则使用绝对偏移量,它不起作用 至于在元素太低时触发的部分,我假设当你说“它总是倾向于滚动一点点越过目标元素,而不是一直滚动到它的末端”时,你指的是如果帧小于它的偏移量,元素就会被切断。请尝试以下操作:
// 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 );
}
//如果框架小于或等于元素的高度
if(frameHeight假设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 );
}
//如果框架小于或等于元素的高度
如果(帧高度