Screen Coordinates of a element, via Javascript

后端 未结 3 1519
悲&欢浪女
悲&欢浪女 2020-12-01 07:47

I\'m trying to get the screen coordinates (that is, relative to the top left corner of the screen) of an element in a browser window. It\'s easy to get the size and position

3条回答
  •  感动是毒
    2020-12-01 08:25

    window.screenX/Y are not supported on IE. But for other browsers, a close approximation of position is:

    var top = $("#myelement").offset().top + window.screenY;
    var left = $("#myelement").offset().left + window.screenX;
    

    Exact position depends on what toolbars are visible. You can use the outer/innerWidth and outer/innerHeight properties of the window object to approximate a little closer.

    IE doesn't provide much in the way of window properties, but oddly enough, a click event object will provide you with the screen location of the click. So I suppose you could have a calibration page which asks the user to "click the red dot" and handle the event with

    function calibrate(event){
        var top = event.screenY;
        var left = event.screenX;
    }
    

    Or possibly use the mouseenter/leave events using the coordinates of that event to calibrate. Though you'd have trouble determining if the mouse entered from the left, right, top, or bottom.

    Of course, as soon as they move the screen you'll need to recalibrate.

    For lots more on browser property compatibilities see PPK's Object Model tables.

提交回复
热议问题