Jquery弹出2许多警报和错误的坐标

Jquery popping 2 many alerts and wrong coordinates

本文关键字:错误 坐标 弹出 许多警 Jquery      更新时间:2023-09-26

G'Evening

我希望 JQuery 在单击图像时弹出警报,然后显示光标在图像中位置的 x 和 y 坐标。

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#blah')
                .attr('src', e.target.result)
                .width(300)
                .height(300)
            $('#blah').mouseenter(function (e) {
                $(this).click(function (e) {
                    alert(e.pageX + ' , ' + e.pageY);
                })
            });
        };
        reader.readAsDataURL(input.files[0]);
    }
}

.HTML:

<input type='file' onchange="readURL(this);" />
  <div id="divfuerimage" height="300px" width="300px" >
    <img id="blah" src="#" alt="your image" style="cursor: pointer"/>
    </div>

现在,当我单击一次并且X和Y坐标来自整个页面时,我随机收到1-5个警报,但我只想要图像中的坐标。

我怎样才能做到这一点?

这是因为每次使用鼠标输入#blah时,单击事件都会被绑定,从而导致重复事件。

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result).width(300).height(300)
            $('#blah').mouseenter(function (e) { /*code for mouseenter*/ });
        };
        reader.readAsDataURL(input.files[0]);
    }
}
$(document).ready(function () {
    $('#blah').on('click', function (e) {
        var offset = $(this).offset(),
            pageX = e.pageX,
            pageY = e.pageY;
        var imgX = pageX-offset.left,
            imgY = pageY-offset.top;
        alert(imgX + ' , ' + imgY);
    });
});

您真正想要的是 readURL 在成功读取文件时创建一个 <img> 元素。

您的坐标问题可以通过使用 this.position(( 来解决

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            if ($('#blah')) {
                $('#blah').remove();
            }
            $('<img id="blah" />')
                .attr('src', e.target.result)
                .width(300)
                .height(300)
                .click(function (e) {
                    window.alert($(this).position().top + ' , ' + $(this).position().left);
                }).appendTo($('#divfuerimage'));
        };
        reader.readAsDataURL(input.files[0]);
    }
}

和你的 HTML:

<input type='file' onchange="readURL(this);" />
<div id="divfuerimage" height="300px" width="300px" >
</div>