【问题标题】:Change div content when hover over link?将鼠标悬停在链接上时更改 div 内容?
【发布时间】:2014-11-14 10:34:49
【问题描述】:

当鼠标悬停在其他文本上时,我想更改 div 的文本。

如何使用 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>

当悬停在上面的链接上时,如何将旧的 p 类替换为新的 p 类,当悬停停止时如何让它返回到原始类?

【问题讨论】:

  • 这也有效 4 me $('a').hover(function () { $('.old').hide(); $('.new').show(); }, 函数 () { $('.old').show(); $('.new').hide(); });使用 css .new { 显示:无; } 我不知道为什么那个帖子被删除了??我是堆栈溢出的新手?但这也是同样的事情,如何在新文本中停留一段时间(制作副本或其他)?它会自动消失,我无法访问新文本?

标签: javascript jquery html


【解决方案1】:

如果您想使用 jQuery,您可能正在寻找 .hover() 函数。

当鼠标进入(和退出)元素时,它接受一个或两个处理程序。

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

这会将原始文本存储在 old 中,并将新文本存储在 now 中(new 是保留字)。 mouseenter 处理程序将文本更改为新文本,mouseexit 处理程序将其更改回原始文本。

为此,您需要将新文本设置为 hidden(参见演示)。

Demo

【讨论】:

【解决方案2】:

@AstroCB 的答案是正确的。

@Css Man:对于您的额外要求,您可以使用 setTimeout 方法。

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

查看演示:http://jsfiddle.net/Teddy_Heaven/42gV5/2/

更新:对于新的 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);
    });
});

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

【讨论】:

猜你喜欢
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 2019-07-30
  • 2015-03-21
  • 2013-07-10
相关资源
最近更新 更多