提问者:小点点

如何使用var输出定位图像?


我正在尝试添加一个功能到我的网站,当一个用户点击在一个随机的位置,一个图像出现在所说的位置。

这是我当前的代码,都在我的html中,我猜我必须使用xposypos作为它们在某种位置标记中的输出?

null

  <script>
    function showCoords(event) {
      var x = event.clientX;
      var y = event.clientY;
      var coords = "X coords: " + x + ", Y coords: " + y;
      document.getElementById("demo").innerHTML = coords;
      document.getElementById("xpos").innerHTML = x;
      document.getElementById("ypos").innerHTML = y;
    
    }
    </script>
      <!DOCTYPE html>
    <html onclick="showCoords(event)" >
    <link rel="stylesheet" href="/style.css">
    <body>
    
    <h2 >Click this heading to get the x (horizontal) and y (vertical) coordinates of the mouse pointer when it was clicked.</h2>
    
    <p><strong>Tip:</strong> Try to click different places in the heading.</p>
    
    
     <img src="https://uploads-ssl.webflow.com/5eed5cc775d5b7fa27c3d7f5/5eef73e7ad8dd5e992850fea_Video-Thumbnail.png" alt="Girl in a jacket" > 
    
     <p id="demo"></p>
     <p id="xpos"></p>
     <p id="ypos"></p>
    
    
     on
  
    
    </body>
    </html>

null


共1个答案

匿名用户

您可以通过使用JS并应用样式,根据单击的线xy使图像位置绝对到该图像来实现这一点

单击snippet屏幕上的任意位置,可以看到img出现/移动到那里。

运行下面的代码段。

null

function showCoords(event) {
  var x = event.clientX;
  var y = event.clientY;
  var coords = "X coords: " + x + ", Y coords: " + y;
  document.getElementById("demo").innerHTML = coords;
  document.getElementById("xpos").innerHTML = x;
  document.getElementById("ypos").innerHTML = y;

  var image = document.getElementById("myImage");
  image.style.display = '';
  image.style.position = 'absolute';
  image.style.left = x + 'px';
  image.style.top = y + 'px';
}
<!DOCTYPE html>
<html onclick="showCoords(event)">
<link rel="stylesheet" href="/style.css">

<body>

  <h2>Click this heading to get the x (horizontal) and y (vertical) coordinates of the mouse pointer when it was clicked.</h2>

  <p><strong>Tip:</strong> Try to click different places in the heading.</p>


  <img id="myImage" src="https://uploads-ssl.webflow.com/5eed5cc775d5b7fa27c3d7f5/5eef73e7ad8dd5e992850fea_Video-Thumbnail.png" alt="Girl in a jacket">

  <p id="demo"></p>
  <p id="xpos"></p>
  <p id="ypos"></p>

</body>

</html>