【问题标题】:JavaScript coordinates showing as greater than the image width and heightJavaScript 坐标显示为大于图像的宽度和高度
【发布时间】:2013-06-24 10:14:15
【问题描述】:

我试图在将鼠标悬停在图像左上角的像素上时获取鼠标的位置。我目前正在使用 pageX 和 pageY 事件属性,但这返回的值大于图像本身的宽度和高度。

var getImgCoord = function(e) {
  var x = e.pageX,
      y = e.pageY;
  console.log(x + ' | ' + y);
}
$('.featuredImg').mousemove(function() {
  getImgCoord(event);
});

任何帮助将不胜感激。

【问题讨论】:

  • 抱歉,图片的左上角,我已经编辑了上面的问题。
  • 你试过clientXclientY吗?
  • 我做到了,clientX 和 clientY 产生了相同的结果。

标签: javascript jquery javascript-events


【解决方案1】:

pageX 和 pageY 是相对于 文档 左上角的坐标,而不是您的图像本身(名称已经说明)。

您需要从元素中减去偏移量:

$('.featuredImg').mousemove(function(e) {
  var x = e.pageX - $(this).offset().left,
      y = e.pageY - $(this).offset().top;
  console.log(x + ' | ' + y);
});

【讨论】:

    【解决方案2】:

    http://jsfiddle.net/D5uuA/

    var getImgCoord = function(e) {
      var imageOffset = $(this).offset(); 
       //or $(this).offset(); if you really just want the current element's offset
       var x = e.pageX - imageOffset.left,
           y = e.pageY - imageOffset.top;
       console.log(x + ' | ' + y);
    }
    $('.featuredImg').mousemove(getImgCoord);
    

    【讨论】:

    • getImgCoord 函数的作用域是什么? $(this) 可能是窗口对象(或 getImgCoord 的当前全局范围),因此您的代码将无法工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    相关资源
    最近更新 更多