我有一个功能,可以滚动以使对象在屏幕上可见。然而,它很慢。有没有办法不用滚动整个页面就跳转到?
如果有一种不使用 jquery 的相当可移植的方法,我更喜欢原生方法。我对相当可移植的定义是它可以在相当新的 chrome 和 firefox 上运行。
function scrollToId(id) { //TODO: Fix Jquery madness below
var element = $('#' + id); //document.getElementById(id);
var offset = element.offset().top;
if (offset > window.innerHeight) {
// Not in view so scroll to it
$('html,body').animate({
scrollTop: offset
}, 10);
return false;
}
return true;
}
最佳答案
快速跳转到页面上某个区域的最佳选择是使用 window.scroll(x, y) 方法。这不会为页面设置动画,但是,它会让您的用户非常快速地到达页面上的该区域。
function scrollToId(id) { //TODO: Fix Jquery madness below
var element = $('#' + id); //document.getElementById(id);
var yPos = element.offset().top;
var xPos = 0; //This could be the left position of an element like element.offset().left
if (offset > window.innerHeight) {
// Not in view so scroll to it
window.scroll(xPos, yPos);
return false;
}
return true;
}
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_scrollto2
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
关于javascript - 快速跳转使 javascript 对象在屏幕上可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32151762/