2016-10-12 5 views
3

여기에 약간의 문제가 있습니다. 나는 자바에 대한 기본적인 지식을 가지고 있으며 다음과 같이하고 싶다.자바 스크립트 - 여러 개의 다른 window.onscroll을 실행하십시오.

지금, 아래로 스크롤하면 메뉴가 작아진다. 다시 올라 가면 정상으로 돌아갑니다. 나는 window.onscroll으로이 이벤트를 호출

var diff = 0; 
function effects(){ 
var topDistance = (document.documentElement &&  document.documentElement.scrollTop) || document.body.scrollTop; 
var clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; 
var clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; 

if(topDistance > diff){ 
    diff = topDistance; 
    if(clientWidth > 1024){ 
     if(topDistance > 300){ 
      document.getElementById("header").style.marginTop= "-100px"; 
     } 
    } 
}else if(topDistance < diff){ 
    diff = topDistance; 
    if(clientWidth > 1024){ 
     if(topDistance > 300){ 
      document.getElementById("header").style.marginTop= "0"; 
     } 
    } 
} 
} 

window.onscroll = effects(); 

가 지금은 또 다른 기능은 동작 버튼에 내 전화에 어떤 효과를 갖고 싶어

, 기능 "테스트"를 호출 할 수 있습니다,하지만 난이 같은 방법으로 수행하려는 경우 위와 같이 효과 함수가 더 이상 작동하지 않습니다.

function test(){ 
//do something 
} 
window.onscroll = test(); 

아무 도움이 없습니다. 나는 그것을하기 위해 큰 도전이되지 않을 tihnk,하지만 내가 잘못하고있는 것 같아요. (PS : 제발 JQUERY NO)

+0

그래서 당신은 스크롤에 두 가지 기능을 호출 할 우선하지 않습니다? 그러나 당신은 또한'effects' 스타일의 헤더와'test' 스타일의 버튼을 원하지만 둘 다 같은 스크롤/오프셋 높이 검사를 원하십니까? – nem035

+1

제쳐두고, onscroll 기능도 디 바운싱하는 것이 좋습니다. https://davidwalsh.name/javascript-debounce-function –

답변

10

당신은 window.onscroll = blabla

을 수행하여 onscroll 함수를 재정의 당신은 할 수 있습니다 :

window.onscroll = function() { 
    effects(); 
    test(); 
} 

또는

window.addEventListener('scroll', effects); 
window.addEventListener('scroll', test); 
+0

간단하면서도 답을 찾기가 쉽지 않습니다. 감사! – Saypontigohe

6

당신은 스크롤 이벤트에 대해 여러 수신기를 사용할 수 있습니다 .

window.addEventListener('scroll', effects); 
window.addEventListener('scroll', test); 

그런 식으로 당신은 window.onscroll

+0

답변 해 주셔서 감사합니다! – Saypontigohe