专家,
我创建了一个图像(#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中取消注释变换旋转,然后运行,我们可以看到鼠标光标的手移动不准确
http://jsfiddle.net/y4pfd7u2/4/
提前致谢!
答案 0 :(得分:1)
好吧,最后我明白了。根据{{3}}的答案,您可以使用下面的rotate
函数找到旋转后点的坐标。以下是问题的最终工作版本(以及this question):
$("#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>
如果您对解决方案或方程式有任何不清楚的地方,请问我。