Javascript mobile Chrome和Safari之间的页面滚动不一致
我的移动web应用程序的一个功能是将用户滚动到页面上的特定点。下面的代码实现了这一点,但它只适用于iPhone Safari。在Chrome浏览器/Android上,它会滚动到页面底部。为什么不一致 请注意:我不想使用jQueryJavascript mobile Chrome和Safari之间的页面滚动不一致,javascript,html,mobile,Javascript,Html,Mobile,我的移动web应用程序的一个功能是将用户滚动到页面上的特定点。下面的代码实现了这一点,但它只适用于iPhone Safari。在Chrome浏览器/Android上,它会滚动到页面底部。为什么不一致 请注意:我不想使用jQuery var $ = function(elID) { return document.getElementById(el); } // Get info about target element's position and dimensions var ge
var $ = function(elID) {
return document.getElementById(el);
}
// Get info about target element's position and dimensions
var getRect = function(el) {
return el.getBoundingClientRect();
}
var scrollJump = function(){
var page = $('dPageContainer');
headerHeight = getRect($('dFixedHeader')).height;
return function(el){
// If a jQuery object, convert to raw DOM el
if ('get' in el) {
el = el.get(0);
}
var rect = getRect(el);
// Scroll the page to the element's position
page.scrollTop+= rect.top - rect.height - headerHeight;
}
};
var scrollToEl = scrollJump();
scrollToEl( $('my_DIV_ID') );
我能够通过简化和清理代码来解决这个问题。特别是,我使用了offsetTop方法,而不是仅依赖getBoundingClientRect:
var $ = function(el) {
return document.getElementById(el);
}
var scrollJump = function(){
var page = $('dPageContainer'),
headerHeight = $('dFixedHeader').getBoundingClientRect().height;
return function(el){
// If a jQuery object, convert to raw DOM el
if ('get' in el) el = el.get(0);
// Scroll the page to the element's position
page.scrollTop = el.offsetTop - headerHeight;
}
};
var scrollToEl = scrollJump();
scrollToEl( $('my_DIV_ID') );