2013-10-12 138 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

相关问题