Display image position based on mouse click coordinates

前端 未结 2 1144
闹比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 02:45

    You can use the CSS element "left" for X and "top" for Y. Make sure to have a "position: absolute;" css style in the image.

    Basically, in code:

    function userClicked() {
        var x = event.clientX;
        var y = event.clientY;
        var snowball = document.getElementById("snowballAppear");
        snowball.style.display = '';
        snowball.style.position = 'absolute';
        snowball.style.left = x + 'px';
        snowball.style.top = y + 'px';
    }
    

    JSFiddle: https://jsfiddle.net/mxq629ng/

    You might want to subtract half the height / width of the image from the X and Y to center it around the mouse.

    EDIT: Addition as some comments came back; you might want to add the "event" as a passable argument in the userClicked function. The click event will forward that "event" variable into your function. This will make it work in many major browsers (somehow it works in V8). Check this Fiddle and it should work in most major browsers; https://jsfiddle.net/mxq629ng/1/

    0 讨论(0)
  • 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";
    }
    
    0 讨论(0)
提交回复
热议问题