ユーザーがランダムな場所をクリックすると、その場所に画像が表示される機能をサイトに追加しようとしています。
これは私の現在のコードです。私は、ある種の位置タグの出力としてHTML
使用する必要があるxpos
とypos
思いますか?
<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>
あなたは、JSを使用してスタイルを適用して画像を作ることによってこれを行うことができますposition
にabsolute
クリックされたコードに応じてその画像にx
し、y
スニペット画面の任意の場所をクリックして、img
表示/移動を確認します。
以下のスニペットを実行します。
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>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加