从< input type ='image'获得点击坐标>通过javascript [英] get click coordinates from <input type='image'> via javascript

查看:78
本文介绍了从< input type ='image'获得点击坐标>通过javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

 < form> 
< input type =imageid ='toothsImage'src =someImg.jpgalt =提交/>
< / form>

图像形式TYPE的行为非常类似于INPUT TYPE = SUBMIT字段,但与SUBMIT字段不同,坐标被激活的图像除了表单数据的其余部分之外还被发送回服务器。所以 - 当一个人点击input = image - 请求将附加点击坐标,如下所示:

  x = 1& y = 2 

我的问题是 - 如何使用javascript检索这些坐标,而不提交表单。 >

PS 1:我知道点击坐标可以通过多种方式进行计算。我知道他们,可以很容易地使用它们。我对这种方法感兴趣,因为这里浏览器会自动计算一切。



PS 2:
我需要得到坐标相对于图像而不是文档。

解决方案

看起来像 offsetX offsetY 不可用或在某些浏览器中不可靠。我建议使用 pageX pageY ,因为这些是通过jQuery进行规范化。结合点击元素的 offset 你应该在这个业务中:

  $(input [type ='image'] ){
var elOffsetX = $(this).offset()。left,
elOffsetY = $(this).offset()。top,
clickOffsetX = event.pageX - elOffsetX,
clickOffsetY = event.pageY - elOffsetY;

// clickOffsetX和clickOffsetY是点击的坐标,
//相对于图像
});

示例: http://jsfiddle.net/andrewwhitaker/87NYk/


Example:

<form>
<input type="image" id = 'toothsImage' src="someImg.jpg" alt="Submit" />
</form>

Image form TYPE acts much like the INPUT TYPE=SUBMIT field, but unlike the SUBMIT field, the coordinates of the image that were activated are sent back to the server in addition to the rest of the form data. So - when one clicks on input=image - request will be appended with click coordinates like so:

x=1&y=2

My question is - how can one retrieve these coordinates using javascript without submitting the form.

P.S 1: I'm aware that click coordinates can be calculated in many ways. I know them and can easily use them. I'm interested in this approach only since here browser calculates everything automatically.

P.S 2: I need to get coordinates that are relative to the image, not the document.

解决方案

Looks like offsetX, offsetY aren't available or are unreliable in some browsers. I would recommend using pageX and pageY since those are normalized by jQuery. Combine that with the offset of the element being clicked and you should be in business:

$("input[type='image']").click(function(event) {
    var elOffsetX = $(this).offset().left,
        elOffsetY = $(this).offset().top,
        clickOffsetX = event.pageX - elOffsetX,
        clickOffsetY = event.pageY - elOffsetY;

    // clickOffsetX and clickOffsetY are the clicked coordinates,
    // relative to the image.
});

Example: http://jsfiddle.net/andrewwhitaker/87NYk/

这篇关于从&lt; input type ='image'获得点击坐标&gt;通过javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆