2013-10-12 34 views
4

當鼠標懸停在單元格的最左側10個像素上時,我需要更改表格單元格的顏色。目前,我有這樣的:鼠標懸停最左邊10px的元素?

$("#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

可你只需要添加一個div 10px的寬到小區的左側和目標上的鼠標懸停呢? – hiattp

回答

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>

+0

你的小提琴似乎沒有做任何事情。 – Keavon

+0

jQuery似乎沒有填充FireFox中的'e.offset'屬性。我發佈了一個修復程序。 – canon

1

把一個div 10px的寬左側和目標,對於鼠標懸停:

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/

+0

Visual Studio給了我警告:'驗證(HTML5):元素'div'不能嵌套在元素'th'中。' – Keavon

+0

真的嗎?我不知道爲什麼它無效的原因。它是否引用驗證錯誤的來源? –

+0

您使用的是舊版本嗎?請參閱:http://connect.microsoft.com/VisualStudio/feedback/details/762026/html5-validator-incorrectly-disallows-div-within-th – hiattp