2011-08-18 2 views
3

답변에 따라 from a previous question, 모두 마우스 위치 (x 및 y 좌표)를 참조하십시오. 문서에자바 스크립트의 마우스 위치와 관련하여 문서 및 뷰포트에 대한 제 이해가 정확합니까?

  • 상대 뷰포트에
  • 상대.

나는 QuirksMode에 관한 기사를 읽었지만 나는 뭔가를 놓친 것 같아. 내 이해를 돕기 위해이 두 다이어그램을 조합했습니다. 내 분석이 맞습니까?

enter image description here

이제 문서 250 픽셀 ...

enter image description here

스크롤

답변

3

귀하의 분석은 (그리고 사람들은 아주 좋은 도면이다!) 올

그러나

다른 게시물에 대한, 그들은 필요한 것보다 조금 더 많은 정보가 있습니다.

문서와 뷰포트가 있다는 것을 이해하면됩니다. 문서는 고정되어 있으며 뷰포트는 사용자와 함께 이동합니다 (스크롤 오프셋이 있음).

원칙적으로 대화 상자 창 중 하나에 상대적으로 배치 할 수 있습니다.

<body> 
<button id="save">Save</button> 
<div id="dialog" style="position:absolute;">Are you sure?</div> 
</body> 

과의 당신이 클릭 할 때 버튼에 해당 요소의 상대적 위치를하고 싶은 말은하자의 대화를 척하자 간단한 분할 요소입니다. 당신은 문서를 사용할 수 있습니다

<script> 
document.getElementById("save").onclick = function(e) { 
    var dialog = document.getElementById("dialog"); 

    dialog.style.top = e.pageY + "px"; 
    /* 
    pageY gives the position of the mouse relative to the 
    document, when this event occurred. 
    */ 
}; 
</script> 

을 아니면 뷰포트 사용할 수 있습니다

<script> 
document.getElementById("save").onclick = function(e) { 
    var dialog = document.getElementById("dialog"); 

    dialog.style.top = e.clientY + window.pageYOffset + "px"; 
    /* 
    clientY gives the position of the mouse relative to 
    the viewport, when this event occurred. And pageYOffset 
    is the distance the user has scrolled. 
    */ 
}; 
</script> 

당신은 심지어 버튼 자체를 사용할 수 있습니다. 이 관계없이 정확하게 사용자가 클릭 한 위치의 당신에게 일관된 입장을주는 추가 혜택이 있습니다

<script> 
document.getElementById("save").onclick = function(e) { 
    var dialog = document.getElementById("dialog"); 

    dialog.style.top = document.getElementById("save").offsetTop + "px"; 
    /* 
    offsetTop gives the position of the button, relative to its nearest 
    positioned ancestor. If the element is deeply nested, you may need 
    to do additional calculations. (jQuery's "offset" method will do this 
    for you). 
    */ 
}; 
</script> 

당신이 jQuery의 대화 상자 클래스를 사용하는 마지막 방법을 적용하려면, 당신은 단순히이 작업을 수행 할 수 있습니다

<script> 
    $("#save").click(function(e) { 
    $("#dialog").dialog({ 
     position: { 
     my: "top", 
     at: "bottom", 
     of: $("#save") 
     } 
     /* 
     See this: http://docs.jquery.com/UI/API/1.8/Position 
     */ 
    }); 
    }); 
</script> 
+0

정말 좋은 첫 번째 대답은 ..imo입니다. – Ahmad

관련 문제