使用鼠标/光标坐标定位弹出窗口

时间:2015-05-08 18:01:02

标签: javascript

我正在使用此代码显示一个弹出窗口,用于phpBB中的迷你配置文件,由鼠标悬停事件触发

<style type="text/css">
.popUpProfile
{
position: absolute;
z-index: 3;
         left: 100px;
        top: 200px;
font-size: 14px;
background-color: #DCEBFE;
margin: 0 10px;
padding: 5px;
width: 450px;
border: solid 2px red;
border-radius: 8px;
resize:both;
overflow:auto;
 
visibility: hidden;
}
</style>

我正在寻找使用鼠标坐标来显示弹出窗口,其顶部与悬停文本处于同一级别,即鼠标y位置,左侧约200px右侧。使用我刚刚找到的代码

<script type="text/javascript">
window.onload = init;
function init() {
	if (window.Event) {
	document.captureEvents(Event.MOUSEMOVE);
	}
	document.onmousemove = getCursorXY;
}

function getCursorXY(e) {
	document.getElementById('cursorX').value = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	document.getElementById('cursorY').value = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
</script>

我现在有x和y变量,称为cursorX和cursorY,但是很难将这些变量放到第一个代码中,因此将坐标传递给弹出窗口。我试过了

left:cursorX +“px”

看起来应该可以在本网站上显示的实例中使用,但事实并非如此!

任何人都可以建议如何传递变量,以及用于获取变量的代码是否尽可能高效?

任何帮助都会受到赞赏(如果这是旧的,我会道歉,但我搜索无济于事!)

干杯!

2 个答案:

答案 0 :(得分:0)

以下代码捕获鼠标坐标并将元素放置在该位置(代码取自this Stack Overflow answer

document.onmousemove = handleMouseMove;
function handleMouseMove(event) {
    var dot, eventDoc, doc, body, pageX, pageY;

    event = event || window.event; // IE-ism

    // If pageX/Y aren't available and clientX/Y are,
    // calculate pageX/Y - logic taken from jQuery.
    // (This is to support old IE)
    if (event.pageX == null && event.clientX != null) {
        eventDoc = (event.target && event.target.ownerDocument) || document;
        doc = eventDoc.documentElement;
        body = eventDoc.body;

        event.pageX = event.clientX +
          (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
          (doc && doc.clientLeft || body && body.clientLeft || 0);
        event.pageY = event.clientY +
          (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
          (doc && doc.clientTop  || body && body.clientTop  || 0 );
    }

    // Use event.pageX / event.pageY here
    //now you must set your elements left and top values dynamically using JavScript
    //This assumes one element with that class name so it takes the first element 
    //returned by getElementsByClassName()
    var myElem = document.getElementsByClassName("popUpProfile")[0];

    myElem.style.left = event.pageX + "px";
    myElem.style.top = event.pageY + "px";
}

答案 1 :(得分:0)

抱歉,是的! (我之前发布时没试过!)