晚安
我希望当我单击图像时,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>
现在,当我点击一次时,我会随机收到 1-5 个警报,并且 X 和 Y 坐标来自整个页面,但我只想要图像中的坐标。
我怎样才能实现这个目标?
最佳答案
这是因为每次用鼠标输入#blah
都会绑定(bind)click事件,导致事件重复。
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);
});
});
关于javascript - Jquery 弹出 2 个许多警报和错误的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25505671/