How to get the MouseEvent coordinates for an element that has CSS3 Transform?
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
andscreenY
return
the screen coordinates (the origin is the top-left corner of user's monitor)clientX
andclientY
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 viewportthis.getBoundingClientRect().left
is
the position of the element relative to the document viewportthis.clientLeft
is
the amount of border (and scrollbar) between the element boundary and the inner coordinatesthis.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?的更多相关文章
- 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 ...
- OpenSceneGraph控制模型
OpenSceneGraph控制模型 转自:http://www.cppblog.com/eryar/archive/2012/05/28/176538.html 一.简介 对模型的控制就是修改模型的 ...
- 【RobotFramework】Selenium2Library类库关键字使用说明
Add CookieArguments:[ name | value | path=None | domain=None | secure=None | expiry=None ]Adds a coo ...
- 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 ...
- cocos2d中的可见性检测
游戏的在进行一次渲染的时候,通常会提交大量的渲染对象给gpu.在这些需要渲染的对象中,并不是所有对象都会出现镜头中,即有一部分对象是不可见的. 通常有两种方式来完成不可见对象的剔除工作: (1)直接交 ...
- js 导出Excel
最近从Silverlight这边转到javascript过来,现在要导出一个导出excel的功能.上级领导指示当页显示多少数据,就导出多少数据,没有必要从后台在去数据.以前也没有接触过这方面的,在网上 ...
- Easy Multiple Copy to Clipboard by ZeroClipboard
要实现在多个复制按钮复制的功能(具体代码在附件中,路径修改一下就行了): <%@ page language="java" import="java.util.*& ...
- 转:VS2008 vs2010中JQUERY智能提醒
第一步: 安装VS 2008 SP1 VS 2008 SP1 在Visual Studio中加了更丰富的JavaScript intellisense支持,对很大部分的JavaScript库加了代码完 ...
- appium点击屏幕(手势)
在android测试过程中,会遇到要点击一下屏幕的需求. 在appium旧版本使用下面代码点击android屏幕,没有报错.Map tap = new HashMap(); tap.put(" ...
随机推荐
- java 用JNA调用dll 参考文档
1 Java调用C语言动态库(JNA方式):回调函数.结构体数组传参.结构体数组返回 2jna结构体数组 JNA结构体数组 3JNA调用C语言动态链接库学习实践总结 4 Java 通过 JNA 调 ...
- TS3
let [first, ...rest] = [1, 2, 3, 4]; console.log(first); // outputs 1 console.log(rest); // outputs ...
- 5. Longest Palindromic Substring[M]最长回文子串
题目 Given a string s, find the longest palindromic substring in s. You may assume that the maximum le ...
- golang sftp传输文件
之前有一篇介绍如何使用 golang 通过SSH协议来执行远程命令:golang执行远程命令 同样,通过SSH协议也可以使用 golang 来远程传输文件. 除了 SSH 的库,为了传输文件,还需要用 ...
- roboware-studio 使用教程
一.创建工作区 1.1 新建工作区 1.2 选择路径并添加工作区的名字 catkin_ws 二.创建程序包 创建ROS包并添加依赖 my_package roscpp std_msgs 三.添加并编写 ...
- 清北集训Day3T1(转换)
这题可能是我与正解里的最近的一次了,可以还是sb的把正解叉了. 正解其实比较显然:因为$f(x)$只有81个取值,所以我们可以枚举$f(x)$,然后计算$x$,再判断$x$是否可以转化为$f(x)$ ...
- Apache-TomCat安装配置
Apache-TomCat安装配置 本文是免安装版的Tomcat!(安装JavaJDK的步骤就不多述了!) (1)官网下载地址:https://tomcat.apache.org/download-8 ...
- 一个APP开发有那么难吗?
app开发 idea:产品设计喵有一个想法. 人员配置: 攻城狮:前端后端服务器齐撸 产品设计:设计原型/UI效果图(界面/交互)齐撸] 流程分析: 1.产品设计喵反复打磨自己的想法,明确要做什么样的 ...
- Eclipse中使用GIT将文件还原至上一版本
GIT将文件还原至上一版本: 选中文件——右击——Replace With——HEAD Revision:
- How to debug systemd step by step
docker run -ti --name systemd --net host --privileged reg.docker.xxxxxxxx:latest /usr/lib/systemd/sy ...