XY光标跟随光标移动

时间:2018-03-31 04:11:17

标签: javascript mouseevent coordinates mouse onmouseover

我希望在身体上有这个光标效果:

https://www.screenshot-magazine.com/

我确实有两个单独的代码,一个用于跟随鼠标的bloc,另一个用于获取xy coords。 但是我太初学了将两者合并在一起,或者两者并行工作,以便在光标移动后在框中打印XY cood。

有人可以帮助我吗? 非常感谢提前:) 安托

这里有两个代码:

小鼠移动后

1-bloc

<style>
#divtoshow {
position:absolute;
display:none;
color: #C0C0C0;
background-color: none;
}

<script type="text/javascript">
var divName = 'divtoshow'; // div that is to follow the mouse (must be position:absolute)
var offX = 15;          // X offset from mouse position
var offY = 15;          // Y offset from mouse position

function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}

function follow(evt) {
var obj = document.getElementById(divName).style;
obj.left = (parseInt(mouseX(evt))+offX) + 'px';
obj.top = (parseInt(mouseY(evt))+offY) + 'px'; 
}

document.onmousemove = follow;
</script>

<body>
<div id='onme' onMouseover='document.getElementById(divName).style.display="block"' onMouseout='document.getElementById(divName).style.display="none"'>
<div id="divtoshow">test</div>

2-get XY coords on body

<script>
function readMouseMove(e){
var result_x = document.getElementById('x_result');
var result_y = document.getElementById('y_result');
result_x.innerHTML = e.clientX;
result_y.innerHTML = e.clientY;
}
document.onmousemove = readMouseMove;
</script>
</head>
<body>

<h2 id="x_result">0</h2>
<h2 id="y_result">0</h3>
</body>

1 个答案:

答案 0 :(得分:0)

你的CSS很好。您可以将#x-result#y-result移至#divtoshow,然后在left中设置rightreadMouseMove。我已经修改了你的代码了。我会在路上解释它

const xResult = document.getElementById("x-result");
const yResult = document.getElementById("y-result");
const divToShow = document.getElementById("divtoshow");

document.onmousemove = function (e) {
  let mouse = {
    x: e.clientX, // this is 2018, so you can just directly use clientX
    y: e.clientY // and clientY
  };

  divToShow.style.left = `${mouse.x + 16}px`; // add a padding so that the text is not rendered directly below the mouse
  divToShow.style.top = `${mouse.y + 16}px`;

  xResult.innerHTML = `X: ${mouse.x}`; // write the text into the output divs
  yResult.innerHTML = `Y: ${mouse.y}`;
};
#divtoshow {
  color: #C0C0C0;
  position: absolute;
}
<div id="divtoshow">
  <span id="x-result">X: 0</span> <br> // i changed the h2s to spans because h2s have HUGE text
  <span id="y-result">Y: 0</span>
</div>

您可以自行添加#onme集成。