简体   繁体   中英

jQuery: toggle text on hover over image?

In jQuery, how can I get text to toggle when the user hovers over an image?

I have code that changes the text when the user hovers:

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

But when the user moves away, the text stays the same - is there a neat way I can get it to toggle back to the original, default text?

Thanks.

Use the two functions of hover (first for mouse over, second for mouse out) then in the first save the oldtext as data on the element. Then read this value and set it in the second function:

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

try :

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

Change your javascript to the following.

$('#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函数

the .hover() method requires TWO parameters. On for what happens when hovering and one for when not hovering. Your code only has the instruction to display the element. You are missing the instruction to remove it again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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