0

我知道使用 CSS,将鼠标悬停在一个元素上不能更改嵌套在给定元素内的元素的属性。因此,我一直在使用 jquery 来更改嵌套在给定元素内的元素的属性。我的代码如下:

<?php
    for($i=0;$i<$count;$i++)
    {
?>   
   <tr>
       <td>Sample</td>
       <td>Text</td>
   </tr>
<?php
    }
?>
<script type="text/javascript">
    $(document).ready(function(){

   $('tr').each(function(index) {
        $(this).hover(function() {  
            $(this).css("color", "#ffffff");    
            $(this).css("background-color", "#0080ff");
        });

        $(this).mouseout(function() {   
            $(this).css("color", "#222222");
            $(this).css("background-color", "#f0f0f0"); 
        });
    });
});
</script>

问题是,一旦我将鼠标悬停在标签上,我就会触发 mouseout 动作,并且字体颜色正在切换回 #222222,我希望它是这样的,只要我将鼠标悬停在标签上或其中任何内容,行的背景颜色设置为#0080ff,字体颜色设置为#ffffff。有什么建议么?

4

3 回答 3

2

我认为您可以使用 CSS 来定位对象内的元素。

在你的情况下:

tr {
    color: #222;
    background-color: #f0f0f0;
}

tr:hover {
    color: #fff;
    background-color: #0080ff;
}

这是jsfiddle

看起来你的 javascript 正在做什么 - 更改 CSS 属性。我是否正确解释了您的问题?

于 2012-10-08T23:28:23.880 回答
0

您应该使用hover(). 您的代码应如下所示:

$('tr').each(function(index) {
        $(this).hover(function() {  
            $(this).css("color", "#ffffff");    
            $(this).css("background-color", "#0080ff");
        }, function(){   
            $(this).css("color", "#222222");
            $(this).css("background-color", "#f0f0f0"); 
        });
});
于 2012-10-08T23:24:13.657 回答
0

您需要mouseleave,因为只有当鼠标完全在元素之外而不是在元素子元素上时才会触发。所以

$(this).mouseout(...)

应该

$(this).mouseleave(...)

或者你可以简单地做

$('tr').each(function(index) {
    $(this).hover(function() {  
        $(this).css("color", "#ffffff");    
        $(this).css("background-color", "#0080ff");
    }, function() {   
        $(this).css("color", "#222222");
        $(this).css("background-color", "#f0f0f0"); 
    });
});

它实际上将第一个函数绑定为mouseenter处理程序,将第二个函数绑定为mouseleave处理程序。

于 2012-10-08T23:24:50.167 回答