我遇到了一些麻烦。 我的主页有 4 个具有不同 id 的 div 元素。 示例:
<div id='one' class='sectionscroll'></div>
<div id='two' class='sectionscroll'></div>
<div id='three' class='sectionscroll'></div>
<div id='four' class='sectionscroll'></div>
所有这些 div 元素都会选择屏幕的高度。 当页面加载时,我自动滚动到 id 为 2 的 div
<div id='two'></div>
。
从这个位置,我想滚动到另一个位置。 但我不明白如何做这个。
这是我的工厂,通过使用 ng-click 缓慢滚动到位置。
(function () {
'use strict';
angular
.module('app.scroll.home.page', [])
.factory('$scrollHomePage', $scrollHomePage);
$scrollHomePage.inject = [];
function $scrollHomePage() {
return {
scrollTo: function(eId) {
var startY = currentYPosition();
var stopY = elmYPosition(eId);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY);
return;
}
var speed = Math.round(distance / 65);
if (speed >= 250) speed = 250;
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() {
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
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;
}
}
};
}
})();
在控制器中我使用了自动滚动
$(window).load(function () {
$("div.sectionscroll").height($('body').height());
$location.hash('');
$scrollHomePage.scrollTo('two');
});
我的答案已经完成。可能有人需要这个。所以享受它。 :)
var currentPosition = 1;
angular.element(document).on("mousewheel DOMMouseScroll", debounce(function(e) {
e.preventDefault();
e.stopPropagation();
var isUp = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? true : false;
if (isUp) {
if (currentPosition > 0) {
currentPosition--;
setPoinerActive();
$scrollHomePage.scrollTo(vm.myIndex[currentPosition]);
}
}
else {
if (currentPosition < 3) {
currentPosition++;
setPoinerActive();
$scrollHomePage.scrollTo(vm.myIndex[currentPosition]); return;
}
}
},300));
嘿@Volodymyr 如果我正确地回答了你的问题,你需要滚动到特定的哈希(
id of div
)
您可以使用 Angular 的 $anchorScroll
和 $location
服务。
下面的代码将滚动到 id 为
output
的 div,如果您想将用户带到比确切 div 低一点的位置,您甚至可以向滚动位置添加偏移量
$anchorScroll.yOffset = 30; // to add extra top margin
$location.hash('output');
$anchorScroll();
然后您可以在按钮或您想要的东西的
ng-click
上调用此函数。