【问题标题】:Moving image with cursor (parent being transform/css rotated)使用光标移动图像(父级正在变换/css 旋转)
【发布时间】:2014-09-29 05:37:46
【问题描述】:

专家,

我创建了一个图像(#hand)移动以及鼠标光标(在 div 内时)。这部分工作正常,除非有一个变换旋转到#handWrap div。手形图像位置在旋转的父 div 上移动不同。我知道,在将 e.pageX 和 e.pageY 位置直接传递给手之前,我们应该进行某种计算,但找不到合适的修复方法。如果有人可以提供帮助,将不胜感激。

HTML:

<div id="handWrap">
    <img id="hand" src="http://s30.postimg.org/s4f5oy9dd/hand.png"/>
</div>

CSS:

* { margin:0; padding:0; }
#handWrap {
    position:absolute;
    top:40px;
    left: 80px;
    width:200px;
    height:300px;
    overflow:hidden;
    border:1px solid red;
    /* try uncommenting below, hand position not being accurate */
    /* transform: rotate(-10deg); */
    cursor:pointer;
}
#hand{
    position: absolute;
    transform: rotate(10deg);
}

jQuery:

$("#handWrap").on("mousemove",function(e){
    // I played with sin/cos/half-width etc, but doesn't worked
    $('#hand').css({'left':e.pageX-130,'top':e.pageY-44});
});

JSfiddle 演示在这里: 在jsfiddle中,尝试取消注释#handWrap中的transform rotate,然后运行,我们可以看到鼠标光标的手部移动不准确

http://jsfiddle.net/y4pfd7u2/4/

提前致谢!

【问题讨论】:

标签: jquery css-transforms


【解决方案1】:

好吧,我终于想通了。根据this question的回答,您可以使用下面的rotate函数找到旋转后点的坐标。这是您的问题的最终工作版本(以及JSFiddle):

$("#handWrap").on("mousemove",function(e){
    // I played with sin/cos/half-width etc, but doesn't worked
    var point = rotate(e.pageX, e.pageY, 100, 150, 10);
    $('#hand').css({'left':point[0]-110,'top':point[1]-30});
});


function rotate(x, y, xm, ym, a) {
    var cos = Math.cos,
        sin = Math.sin,

        a = a * Math.PI / 180, // Convert to radians because that's what
                               // JavaScript likes

        // Subtract midpoints, so that midpoint is translated to origin
        // and add it in the end again
        xr = (x - xm) * cos(a) - (y - ym) * sin(a)   + xm,
        yr = (x - xm) * sin(a) + (y - ym) * cos(a)   + ym;

    return [xr, yr];
}
* { margin:0; padding:0; }
#handWrap {
	position:absolute;
	top:40px; left: 80px;
	width:200px; height:300px;
	overflow:hidden;
	border:1px solid red;
    /* try uncommenting below, hand position not being accurate */
	transform: rotate(-10deg);
    cursor:pointer;
}
#hand{
	position: absolute;
	transform: rotate(10deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="handWrap">
    <img id="hand" src="http://s30.postimg.org/s4f5oy9dd/hand.png"/>
</div>

如果您对解决方案或方程式有任何不清楚的地方,请问我。

【讨论】:

  • Karlen,你让我的一天工作顺利!感谢您的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多