【问题标题】:Jquery text change on hover with transition悬停时带有过渡的Jquery文本更改
【发布时间】:2013-01-03 05:00:26
【问题描述】:

对于这个 HTML sn-p:

<header>
<h1>Title</h1>
<h2>my first sentence</h2>
</header>

我运行这个 Jquery 脚本:

$('header h2').hover(function(){
    $(this).text("my second sentence");
}, function() {
    $(this).text("my first sentence");
});

我想在两种状态之间添加淡入/淡出过渡。

我尝试在 $(this) 之后添加 .fadeIn("slow") 和 .fadeOut("slow") 但它不起作用。能给我一些帮助吗?

PS:我使用 JQuery 而不是 CSS :hover 因为 CSS :before(content) 技巧不适用于过渡:cf。 Change text on hover, then return to the previous text

【问题讨论】:

    标签: jquery fadein fadeout


    【解决方案1】:
    $( function() {
    var fs = $('h2').text();
    var ss = 'my second sentence';
    $('h2').hover(function(){
        $(this).hide().text(ss).fadeIn("slow");
    }, function() {
        $(this).hide().text(fs).fadeIn("slow");
    });
    });
    

    对于fadeIn(),你需要先隐藏()那个元素。我声明了两个不必要的变量,但会对您有所帮助。 var fs(第一句)和var ss(第二句)。

    Fiddle

    【讨论】:

    • 看起来fadeIn 在这里不起作用。还有另一个问题:它的行为不像 CSS :hover
    • 您是否在代码中添加了$(document).ready( function() { });?什么 CSS 悬停?
    • 我刚刚完成了:my first sentence &lt;script type="text/javascript"&gt; $(document).ready( function() { $('h2').hover(function(){ $(this).hide().text("my first sentence").fadeIn("slow"); }, function() { $(this).hide().text("my second sentence (for hover)").fadeIn("slow"); }); }); &lt;/script&gt;
    • 我说 css :hover 因为我想 mouseout = 返回上一个文本。
    • 您的脚本会发生以下情况:当鼠标悬停时,没有任何变化,在鼠标悬停之后(我已经成为鼠标悬停),文本变为“我的第二句话(用于悬停)”。当我回到鼠标悬停时,文本返回到“我的第一句话”。
    【解决方案2】:

    我建议:

    // find the relevant element(s)
    // assign the current text to a custom data-* attribute (for later)
    $('header h2').attr('data-originalText', function () {
        // using this not $(this), since a jQuery object requires more 'work'
        return (this.textContent || this.innerText).trim();
    }).hover(function () {
        // fading out the current element, replacing the text and then fading back in
        $(this).fadeOut(600, function () {
            $(this).text('my new sentence!').fadeIn();
        });
    },
    function () {
        // fading out the current element, replacing the text (from the data-* attribute)
        // and fading back in
        $(this).fadeOut(600, function () {
            $(this).text($(this).attr('data-originalText')).fadeIn();
        });
    });
    

    JS Fiddle demo.

    参考资料:

    【讨论】:

    • 感谢您的回答。它看起来比 Aqib 的要复杂一些,但参考是一种非常有教育意义的方式! (-:
    • 非常感谢您。这也消除了有时使用较长字符串时可能会遇到的任何悬停闪烁
    猜你喜欢
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 2016-09-27
    相关资源
    最近更新 更多