페이지에 버튼이 있습니다. 버튼을 클릭하면 페이지가 지정된 대상으로 스크롤 된 다음 이벤트에 대한 이벤트 리스너 window
를 추가 scroll
하지만 스크롤 이벤트는 다음에 사용자가 스크롤 할 때가 아니라 즉시 트리거됩니다.
아무도 이런 일이 발생하는 이유와 window
지정된 대상으로 스크롤 한 후 스크롤 이벤트를 추가 할 수있는 방법을 말할 수 있습니까? Firefox 37.0.2를 사용하고 있습니다.
HTML
<button>Click Me!</button>
<!-- Enough br tags to make the page have a scroll bar -->
<div id="target">Text</div>
JS
document.getElementsByTagName('button')[0].addEventListener('click', function(){
// Both of the following will trigger the scroll event:
//window.location = '#target';
//document.getElementById('target').scrollIntoView();
window.addEventListener('scroll', function(){
// Removes this function from the window's onscroll event so that it only triggers once
this.removeEventListener('scroll', arguments.callee);
alert('Triggered!');
});
});
댓글을 읽은 후 브라우저가 즉시 스크롤하지 않아 문제가 발생한 것 같습니다. 나는 이것을 1ms setTimeout
지연 시키는 간단한 방법으로 해결할 수 있었다 addEventListener
.
내 수정 된 코드는 다음과 같습니다.
document.getElementsByTagName('button')[0].addEventListener('click', function(){
// Both of the following will work now:
//window.location = '#target';
//document.getElementById('target').scrollIntoView();
setTimeout(function(){
window.addEventListener('scroll', function(){
// Removes this function from the window's onscroll event so that it only triggers once
this.removeEventListener('scroll', arguments.callee);
alert('Triggered!');
});
}, 1);
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다