1

このHTMLスニペットの場合:

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

2つの状態の間にフェードイン/フェードアウト遷移を追加したいと思います。

$(this)の直後に.fadeIn( "slow")と.fadeOut( "slow")を追加しようとしましたが、機能しません。助けてくれませんか。

PS:CSS:before(content)トリックはtransition:cfで機能しないため、CSS:hoverの代わりにJQueryを使用しています。ホバー時にテキストを変更してから、前のテキストに戻ります

4

2 に答える 2

4

私はお勧めします:

// 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 フィドルのデモ

参考文献:

于 2013-01-20T05:01:56.207 に答える
4
$( 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() の場合、最初にその要素を hide() する必要があります。必要のない 2 つの変数を宣言しましたが、役に立ちます。var fs(最初の文) とvar ss(2 番目の文)。

フィドル

于 2013-01-19T17:04:24.107 に答える