2014-09-29 59 views
1

專家,光標移動圖像(父變換/ css旋轉)

我創建了一個圖像(#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}); 
}); 

Ĵ Sfiddle演示在這裏: 在的jsfiddle,嘗試在取消在#handWrap變換旋轉,然後運行,我們可以看到手的動作是不準確的鼠標光標

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

提前感謝!

+0

我試過轉換來源的財產,但沒有工作,http://www.w3schools.com/cssref/css3_pr_transform-origin.asp – 2014-09-29 06:12:16

回答

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 { 
 
\t position:absolute; 
 
\t top:40px; left: 80px; 
 
\t width:200px; height:300px; 
 
\t overflow:hidden; 
 
\t border:1px solid red; 
 
    /* try uncommenting below, hand position not being accurate */ 
 
\t transform: rotate(-10deg); 
 
    cursor:pointer; 
 
} 
 
#hand{ 
 
\t position: absolute; 
 
\t 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>

如果有什麼不太明白你關於溶液或公式,請提問。

+0

卡倫,你讓我的一天工作!感謝您的解釋。 – Shiv 2014-09-29 06:54:44

+0

很高興幫助你! – 2014-09-29 07:21:47