首页 > 解决方案 > 通过鼠标移动在屏幕上书写特定文本

问题描述

我想当我移动鼠标时在屏幕上写下特定的文字

例如:“你好世界”

这是图像(示例)

我有代码,但他不是我想要的

脚本--->


window.focus();
  const output = document.querySelector('output');
  let text = 'A';
  window.addEventListener('mousemove', ({
    x,
    y
  }) => {
    if (x > 100) text = 'W';
    if (x > 400) text = 'X';
    if (y > 100) text = 'B';
    if (y > 400) text = 'J';
    output.textContent += text;
  });

请帮我!!

标签: javascripthtmlcss

解决方案


请注意,我更改了 for,document.querySelector('#output');因为我使用了 id 为“输出”的 div。如果您使用并<output>标记 (?),请将其保留在原始代码中。

这里字母会随着页面滚动而移动,如果您想在滚动时保持在同一位置,请position: static;改用。

  const output = document.querySelector('#output');
  let text = 'Hello World!';
  window.addEventListener('mousemove', ({
      x,
      y
    }) => {
      output.innerHTML += '<div style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;">' + text + '</div>';
  });
<div id="output" style="width: 100%; height: 100%;"></div>


推荐阅读