简体   繁体   English

将鼠标悬停在链接上时更改div内容?

[英]Change div content when hover over link?

I want to change the text of a div when hovering over other text. div悬停在其他文本上时,我想更改div文本。

How do I do it with JavaScript or jQuery? 如何使用JavaScript或jQuery?

<a href="#">change your div text</a>
<div class="original">
   <p class="old">this is my first quesstion on stackoverflow and i hope to be solved</p>
</div>

<p class="new"> the new text i want to add</br>
i will use big text really and i want to change it</p>

How can I replace the old p class with the new p class when hovering over the link above and how can I get it to return to the original class when the hovering stops? 将鼠标悬停在上面的链接上时,如何用新的p类替换旧的p类;当悬停时,如何使它返回到原始类?

If you want to use jQuery, you're likely looking for the .hover() function. 如果要使用jQuery,则可能会寻找.hover()函数。

It accepts either one or two handlers for when the mouse enters (and exits) the element. 当鼠标进入(和退出)元素时,它接受一个或两个处理程序。

var old = $(".old").html();
var now = $(".new").html();
$("a").hover(function(){
    $(".old").html(now);
}, function(){
    $(".old").html(old);
});

This stores the text of your original in old and the new text in now ( new is a reserved word). 这将原来的文本存储在old的文本中,而now将新的文本存储在新文本中( new是保留字)。 The mouseenter handler changes the text to the new text and the mouseexit handler changes it back to the original. mouseenter处理文本更改为新的文本和mouseexit处理程序更改它返回到原来的。

For this to work, you'll need to set your new text to hidden (see demo). 为此,您需要将新文本设置为hidden (请参见演示)。

Demo 演示

The answer of @AstroCB is correct. @AstroCB的答案是正确的。

@Css Man: for your extra requirement, you could use setTimeout method. @Css Man:对于您的额外要求,可以使用setTimeout方法。

var old = $(".old").html();
var now = $(".new").html();
$("a").hover(function(){
    $(".old").html(now);
}, function(){
    setTimeout(function() {
    $(".old").html(old);
    }, 2000);
});

See demo: http://jsfiddle.net/Teddy_Heaven/42gV5/2/ 观看演示: http : //jsfiddle.net/Teddy_Heaven/42gV5/2/

UPDATE: For new 4 steps require: 更新:对于新的4个步骤,需要:

var old = $(".old").html();
var now = $(".new").html();
$("a").hover(function(){
    $(".old").html(now);
}, function(){
    // make time to change your mouse from <a> to <p> (here is 2s)
    var timer = setTimeout(function() {
        $(".old").html(old);
        // if timeout, unbind (A)
        $(".old").unbind('mouseenter mouseleave');
    }, 2000);

    // if you hover <p>, there are new business (A)
    $(".old").hover(function() {
        clearTimeout(timer);
    }, function() {
        $(".old").html(old);
    });
});

Demo: http://jsfiddle.net/Teddy_Heaven/42gV5/6/ 演示: http : //jsfiddle.net/Teddy_Heaven/42gV5/6/

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

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