2011-01-12 2 views
44

내 페이지에 링크가 하나 있다고 가정하고 링크 위로 마우스를 가져 가면 div가 마우스 x, y에 따라 표시됩니다.jQuery를 사용하여 div를 마우스 포인터에 상대적으로 배치하려면 어떻게해야합니까?

jQuery를 사용하여 어떻게하면됩니까?

+0

http://stackoverflow.com/questions/15494357/want-to-show-div-just-under-the-link-using-jquery-when-user-click-on-link 에 http : // 스택 오버플로.com/questions/15635270/이상한 행동 - 드롭 다운 메뉴 - 만든 jquery – Thomas

답변

80
var mouseX; 
var mouseY; 
$(document).mousemove(function(e) { 
    mouseX = e.pageX; 
    mouseY = e.pageY; 
}); 
$(".classForHoverEffect").mouseover(function(){ 
    $('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow'); 
}); 

위의 기능을 사용하면 페이지에있을 수있는 링크 위에 DIV가 표시됩니다. 링크가 밀렸을 때 천천히 페이드 인됩니다. 대신 .hover()를 사용할 수도 있습니다. 마우스를 한 후, 멀리 이동할 때 사라집니다 DIV 싶습니다 그래서 만약 거기에서 DIV는 DIV 이미 배치되어있는 경우

$(".classForHoverEffect").mouseout(function(){ 
    $('#DivToShow').fadeOut('slow'); 
}); 

, 당신은 단순히 또한

$('.classForHoverEffect').hover(function(){ 
    $('#DivToShow').fadeIn('slow'); 
}); 

을 사용할 수, 남아있을 것입니다 DIV 스타일을 fadeIn 또는 표시하려면 display:none;으로 설정해야합니다.

+0

k, 일종의 엉망진창, 정확하지 않은 것을 여기에서 달성하려고 시도했지만 마우스 좌표를 얻을 수 있습니다. 첫 번째 함수 mousemove를 사용하면 변수 mouseX와 mouseY에 변수를 저장합니다. 그런 다음 변수에서 얻고 자하는 거리를 더하거나 뺄 수 있습니다. – mcbeav

+0

답변 해 주셔서 감사합니다. :) – Thomas

+0

확실한 점이 있습니다. 지정된 것이 있거나 더 도움이 필요하면 의견에 여기에 게시하십시오. – mcbeav

-2
<script type="text/javascript" language="JavaScript"> 

    var cX = 0; 
    var cY = 0; 
    var rX = 0; 
    var rY = 0; 

    function UpdateCursorPosition(e) { 
    cX = e.pageX; 
    cY = e.pageY; 
    } 

    function UpdateCursorPositionDocAll(e) { 
    cX = event.clientX; 
    cY = event.clientY; 
    } 
    if (document.all) { 
    document.onmousemove = UpdateCursorPositionDocAll; 
    } else { 
    document.onmousemove = UpdateCursorPosition; 
    } 

    function AssignPosition(d) { 
    if (self.pageYOffset) { 
     rX = self.pageXOffset; 
     rY = self.pageYOffset; 
    } else if (document.documentElement && document.documentElement.scrollTop) { 
     rX = document.documentElement.scrollLeft; 
     rY = document.documentElement.scrollTop; 
    } else if (document.body) { 
     rX = document.body.scrollLeft; 
     rY = document.body.scrollTop; 
    } 
    if (document.all) { 
     cX += rX; 
     cY += rY; 
    } 
    d.style.left = (cX + 10) + "px"; 
    d.style.top = (cY + 10) + "px"; 
    } 

    function HideContent(d) { 
    if (d.length < 1) { 
     return; 
    } 
    document.getElementById(d).style.display = "none"; 
    } 

    function ShowContent(d) { 
    if (d.length < 1) { 
     return; 
    } 
    var dd = document.getElementById(d); 
    AssignPosition(dd); 
    dd.style.display = "block"; 
    } 

    function ReverseContentDisplay(d) { 
    if (d.length < 1) { 
     return; 
    } 
    var dd = document.getElementById(d); 
    AssignPosition(dd); 
    if (dd.style.display == "none") { 
     dd.style.display = "block"; 
    } else { 
     dd.style.display = "none"; 
    } 
    } 
    //--> 
</script> 


<a onmouseover="ShowContent('uniquename3'); return true;" onmouseout="HideContent('uniquename3'); return true;" href="javascript:ShowContent('uniquename3')"> 
[show on mouseover, hide on mouseout] 
</a> 
<div id="uniquename3" style="display:none; 
position:absolute; 
border-style: solid; 
background-color: white; 
padding: 5px;"> 
    Content goes here. 
</div> 
+7

인라인 JavaScript + 이상 코드 = 아니오 좋은 –

+1

복사 본 : –

+1

jQuery가 없습니다! –

7

마우스 x, y를 처리하기 위해 $(document).mousemove(function(e) {})을 만들 필요가 없습니다. $.hover 함수에서 이벤트를 가져오고 거기에서 마우스의 x 및 y 위치를 가져올 수 있습니다. 아래 코드를 참조하십시오 :

$('foo').hover(function(e){ 
    var pos = [e.pageX-150,e.pageY]; 
    $('foo1').dialog("option", "position", pos); 
    $('foo1').dialog('open'); 
},function(){ 
    $('foo1').dialog('close'); 
}); 
9

JQuery를 사용하여 마우스 좌표를 검색하는 예제는 많이 있지만 문제는 해결되지 않았습니다.

내 웹 페이지 본문은 너비가 1000 픽셀이며 사용자의 브라우저 창 중앙에 배치됩니다.

body { 
    position:absolute; 
    width:1000px; 
    left: 50%; 
    margin-left:-500px; 
} 

이제 내 JavaScript 코드에서 사용자가 내 페이지를 마우스 오른쪽 버튼으로 클릭했을 때 마우스 위치에 div가 나타나길 원했습니다.

문제는 단지 e.pageX 값을 사용하는 것이 옳지 않습니다. 내 브라우저 창 크기를 약 1000 픽셀로 조정하면 제대로 작동합니다. 그런 다음 팝 그룹 이 올바른 위치에 나타납니다.

그러나 브라우저 창의 크기를 1200 픽셀로 늘리면 div가 오른쪽의 픽셀로 표시됩니다.

해결 방법은 e.pageX과 body 요소의 경계 사각형을 결합하는 것입니다. 사용자가 브라우저 창의 크기를 변경하면, 몸의 요소가 변경의 값 " 왼쪽", 우리는이 점을 고려해야합니다

// Temporary variables to hold the mouse x and y position 
var tempX = 0; 
var tempY = 0; 

jQuery(document).ready(function() { 
    $(document).mousemove(function (e) { 
     var bodyOffsets = document.body.getBoundingClientRect(); 
     tempX = e.pageX - bodyOffsets.left; 
     tempY = e.pageY; 
    }); 
}) 

휴. 고칠 시간이 좀 걸렸어! 이 기능이 다른 개발자에게 유용하기를 바랍니다.

+2

그것은 ... 똑같은 일을하려하지만, 문제가 생겼습니다. 감사! +1 – william44isme

+0

'top : 50 %;와 같은 수직 오프셋을 수정하려면, margin-top : 500px; ', 또한 'tempY = e.pageY - bodyOffsets.bottom;'을 사용하십시오. 그러나 신체에 위쪽 또는 마진 최고 속성이없는 경우에는 작동하지 않습니다. –

관련 문제