2013-10-12 68 views
1

my previous question上擴展時,如何將div變成紅色,並且鼠標懸停在div的左側10px上時將光標變爲指針,並使div變爲綠色並將鼠標懸停在div的最右邊10px?鼠標懸停最左邊和最右邊10px的元素?

+0

新增指針部分,我的答案,因爲我忘了。 –

+0

雖然你可能不再需要這個答案,但其他人可能在將來 - 我們試圖保持SO作爲新用戶的資源,所以我要稍微改變你的編輯 – Basic

+1

是的,我注意到了,所以我刪除了我的部分關於刪除它人們發佈真正的答案後。我很抱歉通過提出3個問題來創建此類垃圾郵件。 – Keavon

回答

1

下面是基於您以前的代碼/問題的代碼的另一個答案。

http://jsfiddle.net/QL3Sj/2/

$("div").on({ 
    mousemove: function (e) {   
     var $this = $(this); 
     var x = e.offsetX; 
     var width = $(this).width(); 

     // fix for firefox 
     if(typeof x === "undefined"){ 
      x = e.pageX - $this.offset().left; 
     }   
     if (x<= 10) { 
      $this.css("background-color", "red"); 
      $this.css("cursor","pointer"); 
     } 
     else { 
      $this.css("background-color", "white"); 
      $this.css("cursor","default"); 
     } 

     if (x > (width-10)) { 
      $this.css("background-color", "green"); 
      $this.css("cursor","pointer"); 
     }  

    }, 
    mouseleave: function (e) { 
     $(this).css("background-color", "white"); 
     $this.css("cursor","default"); 
    } 
}); 
+1

這一個,雖然更長,更容易修改,以適應我的目的,並沒有離開div保持顏色相同的錯誤。此答案已更改爲最佳答案。 – Keavon

+1

@Keavon是的,我們不希望你必須自己想辦法,我們會嗎?)? –

1

可以使用jQuery的mousemove處理程序,如:

$('div').mousemove(function(e){ 
     var parentOffset = $(this).parent().offset(); 
    //or $(this).offset(); if you really just want the current element's offset 
    var relX = e.pageX - parentOffset.left; 
    var relY = e.pageY - parentOffset.top; 
    if(relX <= 10) $(this).css({'background-color':'red','cursor':'pointer'}); 
    else if(relX > ($(this).width() -10)) $(this).css({'background-color':'green','cursor':'pointer'}); 
    else 
     $(this).css({'background-color':'gray','cursor':'auto'}); 
}); 

http://jsfiddle.net/kPK83/1/

相對元素定位來自this answer

相關問題