jQuery:在鼠标悬停在图片上时切换文字?

时间:2011-07-29 14:34:10

标签: javascript jquery

在jQuery中,当用户将鼠标悬停在图像上时,如何让文本切换?

我有代码在用户悬停时更改文本:

# HTML
<table id="support-people">
<tr>
<td><img data-bio="Bio 1" src="person1.jpg" alt="Person 1"/></td>
<td><img data-bio="Bio 2" src="person2.jpg" alt="Person 2"/></td>
</tr>
<tr><td colspan="2">
<p id="support-person-description">Default text</p>
</td></tr></table>

# JS
$('#support-people img').hover(function(){
    $('#support-person-description').text(this.getAttribute("data-bio"));
});

但是当用户离开时,文字保持不变 - 有没有一种简洁的方法可以让它切换回原始的默认文本?

感谢。

5 个答案:

答案 0 :(得分:3)

使用悬停的两个功能(首先用于鼠标悬停,第二个用于鼠标输出)然后在第一个中将oldtext保存为元素上的数据。然后读取该值并在第二个函数中设置它:

$('#support-people img').hover(function(){
    var desc = $('#support-person-description');
    desc.data('oldtext', desc.text()).text(this.getAttribute("data-bio"));
}, function() {
    var desc = $('#support-person-description');
    desc.text(desc.data('oldtext'));
});

答案 1 :(得分:1)

尝试:

$('#support-people img').hover(function(){
    var $elem = $('#support-person-description');
    $elem.data('oldText', $elem.text()).text(this.getAttribute("data-bio")); // Add text on mouse hover
},function(){
    var $elem = $('#support-person-description');
    $elem.text($elem.data('oldText')); // Return to default
});

答案 2 :(得分:0)

将您的javascript更改为以下内容。

$('#support-people img').hover(function(){
    $('#support-person-description').text(this.getAttribute("data-bio"));
}, function(){
    $('#support-person-description').text('Default text');
});

答案 3 :(得分:0)

您可以在同一个调用中编写onMouseOver和onMouseOut函数 http://api.jquery.com/hover/

答案 4 :(得分:0)

.hover()方法需要两个参数。关于悬停时发生的情况以及不悬停时发生的情况。您的代码只有显示元素的指令。您错过了再次删除它的说明。

相关问题