我正在尝试使用javascript和jquery更改HTML元素的文本。到目前为止,这是我的代码,但似乎无法正常工作。我已经用谷歌搜索,似乎找不到任何东西。

$("div#title").hover(
    function() {
        $(this).stop().animate({
            $("div#title").html("Hello")
        }, "fast");
    },
    function(){
        $(this).stop.animate({
            $("div#title").html("Good Bye")
        }, "fast");
    }
);

任何帮助将不胜感激。

最佳答案

当前的语法方式是不正确的,而且您不能为文本设置动画,而是需要为包含文本的元素设置动画。同样不清楚您要设置动画效果,以下是两个示例:

动画不透明度:

$("div#title").hover(

function () {
    $(this).stop().css('opacity', '0').html(function (_, oldText) { // Set the opacity of the div to 0 and then change the html (flip it based on last value)
        return oldText == 'Good Bye' ? 'Hello' : 'Good Bye'
    }).animate({
        opacity: 1 // Animate opacity to 1 with a duration of 2 sec
    }, 2000);
});

Fiddle

动画宽度:
$("div#title").hover(

function () {
    $(this).stop().animate({
        'width': '0px'  // Animate the width to 0px from current width
    }, 2000, function () {  // On completion change the text
        $(this).html(function (_, oldText) {
            return oldText == 'Good Bye' ? 'Hello' : 'Good Bye'
        }).animate({          // and animate back to 300px width.
            'width': '300px'
        }, 2000);
    })
});

Fiddle

09-25 16:56
查看更多