Display image position based on mouse click coordinates

前端 未结 2 1145
闹比i
闹比i 2021-01-14 02:04

I start with a blank page, and the user is supposed to click anywhere on the page to make an image pop up. I\'m trying to display an image at the exact coordinates of where

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 03:07

    You need to position the img element:

    Dont't forget to pass in the event to your function

    function userClicked(event) {
        var x = event.clientX;
        var y = event.clientY;
        document.getElementById("xCoord").innerHTML=x;
        document.getElementById("snowballAppear").style.display = '';
        // fixed position - The element is positioned relative to the browser window
        document.getElementById("snowballAppear").style.position = "fixed";
        // px from top of browser
        document.getElementById("snowballAppear").style.top  = y + "px";
        // px from left of browser
        document.getElementById("snowballAppear").style.left = x + "px";
    }
    

提交回复
热议问题