鼠标悬停最左边10px的元素?

时间:2013-10-12 18:34:24

标签: javascript jquery html

当鼠标悬停在单元格的最左侧10个像素上时,我需要更改表格单元格的颜色。目前我有这个:

$("#myTable table thead tr th:nth-child(3)").mouseover(function () {
    $(this).css("background-color", "red");
});
$("#myTable table thead tr th:nth-child(3)").mouseout(function () {
    $(this).css("background-color", "white");
});

这适用于悬停在整个元素上,但我只需将它悬停在最左边的10px上就可以了。

2 个答案:

答案 0 :(得分:4)

您可以使用mousemove代替检查偏移坐标:

$("div").on({
    mousemove: function (e) {        
        var $this = $(this);
        var x = e.offsetX;
        
        // fix for firefox
        if(typeof x === "undefined"){
           x = e.pageX - $this.offset().left;     
        }        
        
        $this.css("background-color", x <= 10 ? "red" : "white");
    },
    mouseleave: function (e) {
        $(this).css("background-color", "white");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>test test test test</div>

答案 1 :(得分:1)

将一个10px宽的div放在左侧并将其作为鼠标悬停的目标:

<强> HTML

<th>
  <div class="hover-target"></div>
  <p>Name</p>
</th>

<强> JS

$(function () {
  $("#myTable thead tr .hover-target").mouseover(function () {
    $(this).parent().css("background-color", "red");
  });
  $("#myTable thead tr .hover-target").mouseout(function () {
    $(this).parent().css("background-color", "white");
  });
});

http://jsfiddle.net/FDRm8/

相关问题