繁体   English   中英

jQuery:在悬停在图像上切换文本?

[英]jQuery: toggle text on hover over image?

在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"));
});

但是当用户离开时,文本保持不变-是否有一种巧妙的方法可以使它切换回原始的默认文本?

谢谢。

使用鼠标悬停的两个功能(第一个用于鼠标悬停,第二个用于鼠标悬停),然后在第一个中将旧文本另存为元素上的数据。 然后读取该值并在第二个函数中进行设置:

$('#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'));
});

尝试:

$('#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
});

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

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

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

.hover()方法需要两个参数。 当悬停时发生什么,不悬停时发生。 您的代码仅具有显示元素的指令。 您缺少再次删除它的说明。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM