在my previous question上延伸,当鼠标悬停在div的左侧10px上时,如何使div变为红色并且光标变为指针,并使div变为绿色并将光标转到a将鼠标悬停在最右边10px的div上时指针?
答案 0 :(得分: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'});
});
相对元素定位来自this answer。
答案 1 :(得分:1)
以下是基于您之前的代码/问题的代码的另一个答案。
$("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");
}
});