1

扩展我之前的问题,当鼠标悬停在 div 的左侧 10px 上时,如何使 div 变为红色并将光标变为指针,并在将鼠标悬停在 div 上时使 div 变为绿色并将光标变为指针div最右边的10px?

4

2 回答 2

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");
    }
});
于 2013-10-12T20:52:16.887 回答
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

于 2013-10-12T20:43:33.930 回答