2015-03-31 60 views
0

我想滚动到我的应用程序的特定目标 - 是这样的:scrollTop的偏移时改变

var editor = self.$el.find(".editorWrapper[data-containerid=" + containerId + "]").closest('.containerWrapper'); 
$('html, body').animate({ 
    scrollTop: editor.position().top-5 
}, 1000); 

的问题是,有哪个渲染,同时向下滚动元素 - >例如图像或iframe在向下滚动时呈现。我不知道该新渲染元素的高度(难以获得高度 - 但并非不可能),滚动停在错误的位置。有一种简单的方法可以顺利滚动到一个元素,而偏移量/高度变化,然后保存每个“新渲染”元素的高度?

回答

1

我只要向下滚动,直到它实际找到特定点。例如:

function ScrollTo(el) { 
 
    if ($('html').scrollTop() < (el.position().top - 5)) { 
 
     $('html').animate({ 
 
      scrollTop: $('html').scrollTop() + 1 
 
     }, 1, 'swing', function() { 
 
      ScrollTo(el);    
 
     }); 
 
    } 
 
} 
 
ScrollTo($('#scrollTo'));
div { 
 
    width:400px; 
 
} 
 
#large { 
 
    height:400px; 
 
    background:red; 
 
} 
 
#scrollTo { 
 
    height:400px; 
 
    background:green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="large"></div> 
 
<div id="scrollTo"></div>

你可以玩的设置,使其滚动在一个体面的速度为你等

+0

伟大的事情!工作:) – 2015-03-31 15:10:49

0

您希望自己的网页完全加载,你可以打电话给你的脚本中:

$(document).load(function() { 
    var editor = self.$el.find(".editorWrapper[data-containerid=" + containerId + "]").closest('.containerWrapper'); 
    $('html, body').animate({ 
    scrollTop: editor.position().top-5 
}, 1000); 
}); 

https://api.jquery.com/load-event/

+0

啊 - 但我使用“lazyload”技术一个原因。我使用http://embed.ly/,并且我不希望客户端加载所有内容,即使它不在视口中。 – 2015-03-31 13:49:19

0

滚动条的位置很可能将每次改变图像/ iframe中获取呈现,所以最好方式是将加载事件绑定到更新scrollTop位置的这些元素(image/iframe)。

+0

这是一个好点 - 但我怎么能动态地添加一个偏移量,而它是滚动?:) – 2015-03-31 14:11:05

+0

我做了一个快速演示:http://jsfiddle.net/jq2hfmnf/1/ – 2015-04-01 08:21:21

+0

真的很感激它;)谢谢!也看看杰米·巴克的答案;) – 2015-04-01 08:59:40