簡體   English   中英

jQuery懸停效果超過表

[英]jQuery hover effect over table

我是jQuery的新手,我試圖在我的桌子上做一個懸停效果,但我不知道如何。 我想只將文本設為紅色,然后在焦點丟失時再次刪除紅色。

這是我到目前為止:

<script type="text/javascript">
$(function() {
    $('tr').hover(function() {
        $(this).css('color', 'red')
    });
});
</script>


<table border="1">
    <tr>
        <th>ID</th>
        <th>name</th>
    </tr>
    <tr>
        <td>#1</td>
        <td>ole</td>
    </tr>
    <tr>
        <td>#2</td>
        <td>jeffrey</td>
    </tr>
    <tr>
        <td>#3</td>
        <td>collin</td>
    </tr>
    <tr>
        <td>#4</td>
        <td>eve</td>
    </tr>
</table>

您需要做的就是傳遞另一個函數來懸停鼠標離開。

$('tr').hover(function() {
    $(this).css('color', 'red');
}, function() {
    $(this).css('color', '');
});

請參閱jsfiddle上的示例

或者你也可以只在css中做到這一點。

tr:hover{
    color:red;
}

IE 5/6僅支持鏈接。 IE 7支持:在所有元素上懸停,但不支持:活動。 這里開始

您需要在懸停時添加處理程序。 在這里查看: http//jsfiddle.net/bF9xy/ documentation here: http//api.jquery.com/hover/

$(function() {
    $('tr').hover(function() {
        $(this).css('color', 'red')
    },function() {
        $(this).css('color', 'black')
    }
);
});

jQuery中的.hover()函數有兩個參數:一個用於事件中鼠標的函數,另一個用於鼠標輸出的函數:

$('dom element').hover(function()
{
    //your code for mouse over
}, function()
{
   //your code for mouse out
});

PS:一般來說,在像你這樣的情況下,最好更改元素的類而不是css屬性本身。 使用.addClass()和.removeClass()。 這樣,通過更改css而不是javascript,將來更容易獲得懸停效果。

<style type="text/css">
.highlight { background-color:red; }
<style>
<script>
$(
 function()
 {
  $("table>tr").hover(
   function()
   {
    $(this).addClass("highlight");
   },
   function()
   {
    $(this).removeClass("highlight");
   }
  )
 }
)
</script>

一點解決方法:

<html>
    <head>
        <script type="text/javascript">
            $(document).ready(function(){
                $('tr').hover(function() {
                    $(this).css('color', 'red')
                });
                $('tr').mouseout(function() {
                    $(this).css('color', 'black')
                });
            });
        </script>
    </head>
    <body>
        <table border="1">
            <tr>
                <th>ID</th>
                <th>name</th>
            </tr>
            <tr>
                <td>#1</td>
                <td>ole</td>
            </tr>
            <tr>
                <td>#2</td>
                <td>jeffrey</td>
            </tr>
            <tr>
                <td>#3</td>
                <td>collin</td>
            </tr>
            <tr>
                <td>#4</td>
                <td>eve</td>
            </tr>
        </table>
    </body>
</html>/

由於樣式通常比紅色文本更復雜,您可以考慮使用此路徑:

$(function() {
$('tr').hover(function() {
    $(this).toggleClass('redHover')
        }, function() {
    $(this).toggleClass('redHover')
    });
});

redHover會是這樣的

<style>
.redHover{
    color:red;
}
</style>

然后你可以改變風格,而無需重寫你的jQuery。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM