Javascript鼠标单击图像的坐标 [英] Javascript mouse click coordinates for image

查看:107
本文介绍了Javascript鼠标单击图像的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作业说:您的任务是编写一个包含JavaScript的HTML文件,该HTML文件将随机显示上面的图像之一.如果在浏览器中刷新了页面,则应该获得另一张随机图像."所以我做到了

The assignment says "Your task is to write an HTML file that contains JavaScript that will randomly display one of the images above. If the page is refreshed in the browser, you should get another random image." so I did it.

现在它说:当用户单击图像上的任何位置时,将显示一个警报窗口,其中显示单击发生的位置相对于图像的X和Y位置".这是我的代码:

Now it says "When the user clicks anywhere on the image, display an alert window that shows the X and Y position of where the click occurred relative to the image". Here is my code:

<html>
<head>
<title>Assignment 2</title>
<script type="text/javascript">
  var imageURLs = [
       "p1.jpg"
     , "p2.jpg"
     , "p3.jpg"
     , "p4.jpg"
  ];
  function getImageTag() {
    var img = '<img src=\"';
    var randomIndex = Math.floor(Math.random() * imageURLs.length);
    img += imageURLs[randomIndex];
    img += '\" alt=\"Some alt text\"/>';
    return img;
  }
</script>
</head>
<body>
<script type="text/javascript">
  document.write(getImageTag());
</script>
</body>
</html>

推荐答案

您实际上可以为此使用HTML.图像标签具有称为ismap的属性.

You can actually use HTML for this. The image tag has an attribute known as ismap.

此属性的作用是指定图像是服务器端图像映射的一部分.在此类地图上单击时,单击坐标将作为url查询字符串发送到服务器.

What this attribute does is specify that an image is part of a server-side image map. When clicking on such map, the click coordinates are sent to the server as a url query string.

图像必须嵌套在链接下才能起作用.这是一个例子

Images must be nested under links for this to work. Here is an example

<a href="http://www.google.com">
    <img src="myimage.png" alt="My Image" ismap">
</a>

如果您不能为此使用图片映射,请使用javascript/jquery解决方案

If you can't use image maps for this, here is a javascript/jquery solution

首先,您需要在body标签底部添加jQuery库.

First, you need to include the jQuery library at the bottom of your body tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  

$(document).ready(function() {
    $("img").on("click", function(event) {
        var x = event.pageX - this.offsetLeft;
        var y = event.pageY - this.offsetTop;
        alert("X Coordinate: " + x + " Y Coordinate: " + y);
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="http://vignette1.wikia.nocookie.net/seraphina/images/b/b2/Dragonseraphina.jpg/revision/latest?cb=20160103194957" height="200" width="200" alt="dragon">

您监听click事件,并将事件作为参数传递.

You listen for the click event, and pass in event as the parameter.

event.pageX属性返回鼠标指针相对于文档左边缘的位置.

The event.pageX property returns the position of the mouse pointer, relative to the left edge of the document.

这篇关于Javascript鼠标单击图像的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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