I want to detect where a MouseEvent has
occurred, in coordinates relative to the clicked element. Why? Because I want to add an absolutely positioned child element
at the clicked location.

I know how to detect it when no CSS3 transformations exist (see description below). However, when I add a CSS3 Transform, then my algorithm breaks, and I don't know how to fix it.

I'm not using any JavaScript library, and I want to understand how things work in plain JavaScript. So, please, don't answer with "just use jQuery".

By the way, I want a solution that works for all MouseEvents, not just "click". Not that it matters, because I believe all mouse events share the same properties, thus the same solution should work for all of them.


Background information

According to DOM
Level 2 specification
, a MouseEvent has
few properties related to getting the event coordinates:

  • screenX and screenY return
    the screen coordinates (the origin is the top-left corner of user's monitor)
  • clientX and clientY return
    the coordinates relative the document viewport.

Thus, in order to find the position of the MouseEvent relative
to the clicked element content, I must do this math:

ev.clientX - this.getBoundingClientRect().left - this.clientLeft + this.scrollLeft
  • ev.clientX is
    the coordinate relative to the document viewport
  • this.getBoundingClientRect().left is
    the position of the element relative to the document viewport
  • this.clientLeft is
    the amount of border (and scrollbar) between the element boundary and the inner coordinates
  • this.scrollLeft is
    the amount of scrolling inside the element

getBoundingClientRect()clientLeft and scrollLeft are
specified at CSSOM
View Module
.

Experiment without CSS Transform (it works)

Confusing? Try the following piece
of JavaScript and HTML
. Upon clicking, a red dot should appear exactly where the click has happened. This version is "quite simple" and works as expected.

function click_handler(ev) {
var rect = this.getBoundingClientRect();
var left = ev.clientX - rect.left - this.clientLeft + this.scrollLeft;
var top = ev.clientY - rect.top - this.clientTop + this.scrollTop; var dot = document.createElement('div');
dot.setAttribute('style', 'position:absolute; width: 2px; height: 2px; top: '+top+'px; left: '+left+'px; background: red;');
this.appendChild(dot);
} document.getElementById("experiment").addEventListener('click', click_handler, false); <div id="experiment" style="border: 5px inset #AAA; background: #CCC; height: 400px; position: relative; overflow: auto;">
<div style="width: 900px; height: 2px;"></div>
<div style="height: 900px; width: 2px;"></div>
</div>

Experiment adding a CSS Transform (it fails)

Now, try adding a CSS transform:

#experiment {
transform: scale(0.5);
-moz-transform: scale(0.5);
-o-transform: scale(0.5);
-webkit-transform: scale(0.5);
/* Note that this is a very simple transformation. */
/* Remember to also think about more complex ones, as described below. */
}

The algorithm doesn't know about the transformations, and thus calculates a wrong position. What's more, the results are different between Firefox 3.6 and Chrome 12. Opera 11.50 behaves just like Chrome.

In this example, the only transformation was scaling, so I could multiply the scaling factor to calculate the correct coordinate. However, if we think about arbitrary transformations (scale, rotate, skew, translate, matrix), and even nested transformations
(a transformed element inside another transformed element), then we really need a better way to calculate the coordinates.

How to get the MouseEvent coordinates for an element that has CSS3 Transform?的更多相关文章

  1. Why AlloyFinger is so much smaller than hammerjs?

    AlloyFinger is the mobile web gesture solution at present inside my company, major projects are in u ...

  2. OpenSceneGraph控制模型

    OpenSceneGraph控制模型 转自:http://www.cppblog.com/eryar/archive/2012/05/28/176538.html 一.简介 对模型的控制就是修改模型的 ...

  3. 【RobotFramework】Selenium2Library类库关键字使用说明

    Add CookieArguments:[ name | value | path=None | domain=None | secure=None | expiry=None ]Adds a coo ...

  4. pageX/Y, offset(), position(), scrollTop(), screenX/Y, clientX/Y, pageX/Y

    event.pageX get mouse position Description: The mouse position relative to the left edge of the docu ...

  5. cocos2d中的可见性检测

    游戏的在进行一次渲染的时候,通常会提交大量的渲染对象给gpu.在这些需要渲染的对象中,并不是所有对象都会出现镜头中,即有一部分对象是不可见的. 通常有两种方式来完成不可见对象的剔除工作: (1)直接交 ...

  6. js 导出Excel

    最近从Silverlight这边转到javascript过来,现在要导出一个导出excel的功能.上级领导指示当页显示多少数据,就导出多少数据,没有必要从后台在去数据.以前也没有接触过这方面的,在网上 ...

  7. Easy Multiple Copy to Clipboard by ZeroClipboard

    要实现在多个复制按钮复制的功能(具体代码在附件中,路径修改一下就行了): <%@ page language="java" import="java.util.*& ...

  8. 转:VS2008 vs2010中JQUERY智能提醒

    第一步: 安装VS 2008 SP1 VS 2008 SP1 在Visual Studio中加了更丰富的JavaScript intellisense支持,对很大部分的JavaScript库加了代码完 ...

  9. appium点击屏幕(手势)

    在android测试过程中,会遇到要点击一下屏幕的需求. 在appium旧版本使用下面代码点击android屏幕,没有报错.Map tap = new HashMap(); tap.put(" ...

随机推荐

  1. 并发编程网 - ifeve.com

    并发编程网 - ifeve.com 让天下没有难学的技术 首页 JAVA 深入浅出ClassLoader 深入浅出ClassLoader Dedicate to Molly. 你真的了解ClassLo ...

  2. 在SAE上使用Ueditor的图片上传功能

    SAE上是没有文件夹读写权限的,所以要在SAE使用Ueditor的图片上传功能须要借助SAE的Storage服务. 一.开通Storage服务 在SAE控制台开通Storage服务,并新增一个doma ...

  3. Fatal error: Incompatible file format: The encoded file has format major ID 1...解决方式

    申请好域名和空间后.将站点源代码上传到空间,解析好域名后.在地址栏输入域名出现以下错误: Fatal error: Incompatible file format: The encoded file ...

  4. 在 Eclipse 中使用 C++

    安装 安装Eclipse Eclipse下载页 能够选择Eclipse IDE for C/C++ Developers(内置CDT插件) 也能够选择安装其它版本号之后再安装CDT插件. 安装CDT插 ...

  5. 0x28 IDA*

    一个早上做完了我真牛B 就是A*用于DFS啊,现在我才发现迭代加深真是个好东西. poj3460 %了%了我们的目标是把它的顺序变对,那么第i个位置的值+1是要等于第i+1个位置的值的.对于一个操作, ...

  6. php后期静态绑定

    php后期静态绑定 自 PHP 5.3.0 起,PHP 增加了一个叫做后期静态绑定的功能,用于在继承范围内引用静态调用的类. 虽然也可以调用非静态方法,但是不会在运行时绑定. static 不再只是简 ...

  7. Java-MyBatis:MyBatis 中 in 的用法

    ylbtech-Java-MyBatis-杂项:MyBatis  中  in 的用法 1.返回顶部 1. foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合.foreach元 ...

  8. 杂项-公司:YKK

    ylbtech-杂项-公司:YKK YKK的全称为Yoshida Kogyo Kabushikigaisha.YKK是拉链行业的鼻祖,代表着行业标准,因为采用日本精确的工艺,原料和管理方法,YKK价格 ...

  9. BZOJ 4522 Pollard-rho+exgcd

    思路: N=P*Q 求出来P和Q 模拟就好- //By SiriusRen #include <cstdio> #include <algorithm> using names ...

  10. javascript中手风琴特效

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...