在我的网站上,我希望我的页面滚动到我感兴趣的ID。 我在stackoverflow上找到了这个很好的代码,它完全符合我的需要(我只是对原版进行了一些编辑)
var $scope, $location;
var headerHeigh = 50;
angular.module('allApps').service('anchorSmoothScroll', function(){
this.scrollTo = function(eID) {
var startY = currentYPosition();
var stopY = elmYPosition(eID)-headerHeigh;
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 50);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer*speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
};
});
angular.module('allApps').controller('menuCtrl', function($scope, $location, anchorSmoothScroll) {
$scope.gotoElement = function (eID){
$location.hash(eID);
anchorSmoothScroll.scrollTo(eID);
};
});
我的问题是:为什么我改为编写此代码
setTimeout(function(){
window.scrollTo(0, leapY);
}, timer*speed);
我失去了“滚动效果”?
我想这样做的原因是因为我想和滚动一起想要一些效果,比如滚动时不透明度会发生变化,所以我想进入setTimeout会有一个带有多个操作的函数。
感谢您的帮助
答案 0 :(得分:0)
您可以在for循环中使用此代码:
(function(leapY) {
setTimeout(function(){
window.scrollTo(0, leapY);
}, timer*speed);
})(leapY);