I am using the following function in a single page application in Angular. When I click on the menu item, I scroll to the relevant div.
scroll (el) {
this.sharedService.isClicked.next(true);
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
How do I check if the element has finished scrolling? I want to avoid the setTimeout
function.
I am using the following function in a single page application in Angular. When I click on the menu item, I scroll to the relevant div.
scroll (el) {
this.sharedService.isClicked.next(true);
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
How do I check if the element has finished scrolling? I want to avoid the setTimeout
function.
- Related: stackoverflow./questions/46795955/… – gbelisario Commented Oct 17, 2018 at 4:45
3 Answers
Reset to default 2This worked for me (I declare this snippet public domain, feel free to re-use):
scrollAndDo = function(currPageXOffset,currPageYOffset) {
$('#SomeElement')[0].scrollIntoView({behavior: 'smooth',block:'nearest',inline: 'nearest'});
currPageXOffset = window.pageXOffset;
currPageYOffset = window.pageYOffset;
var scrollDone = setInterval(function () {
if ( currPageXOffset == window.pageXOffset && currPageYOffset == window.pageYOffset ) {
clearInterval(scrollDone);
console.log('I have finished scrolling');
}
currPageXOffset = window.pageXOffset;
currPageYOffset = window.pageYOffset;
},50);
};
scrollAndDo();
hope this helps..
var scrollIntoviewCompleted = false;
var currentVisible = false;
var onceVisible = false;
$(window).scroll(function(){
$.fn.isOnScreen = function(){
var element = this.get(0);
var bounds = element.getBoundingClientRect();
return bounds.top < window.innerHeight && bounds.bottom > 0;
}
if ($('.targetdiv').isOnScreen()) {
currentVisible = true;
onceVisible =true;
}
else
{
currentVisible = false;
}
if(onceVisible == true && currentVisible == false){
scrollIntoviewCompleted = true;
console.log("scrollIntoViewCompleted");
}
});
Based on an answer in this question I was able to make this for my tests... and this assumes that you are @Inject
ing window
into your angular ponents
let win: Window;
const onScrollEnd = (fn: () => void): void => {
let scrollTimeout: number | undefined;
const listener = (): void => {
win.clearTimeout(scrollTimeout);
scrollTimeout = win.setTimeout(() => {
win.removeEventListener('scroll', listener);
fn();
}, 100);
};
win.addEventListener('scroll', listener);
};
beforeEach(() => {
//Standard ponent test setup stuff goes here...
win = TestBed.get('Window');
});
And then in my test I can do this:
it('should scroll the window down when...', (done: DoneFn) => {
ponent.shouldScroll = true;
fixture.detectChanges();
onScrollEnd(() => {
expect(win.scrollY).toBeGreaterThan(0);
done();
});
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744872484a4598344.html
评论列表(0条)