【问题标题】:Can't animate letters (wrapped with span tag) inside the DIV with jQuery animate method无法使用 jQuery animate 方法为 DIV 内的字母(用 span 标签包装)设置动画
【发布时间】:2016-06-02 10:08:26
【问题描述】:
var letter = $("div#text").children().first();
letter.animate({
    opacity:"0.5"
},3000) // works!


var allLetters = $("span");
allLetters[1].animate({
    opacity:"0.5"
},3000) // it doesnt works

这是我的小提琴:https://jsfiddle.net/n40af9dh/

当我通过 jQuery 遍历 DOM 方法对持有对 span 对象的推断的 letter 变量调用动画方法时: $("div#text").children().first() 它可以工作。但是,当我在以下位置调用相同的方法时:

var allLetters = $("span");
allLetters[1].animate({
    opacity:"0.5"
},3000) 

它不起作用,控制台输出以下错误:

未能在“元素”上执行“动画”:部分关键帧不是 支持。

【问题讨论】:

    标签: jquery dom


    【解决方案1】:

    问题是因为通过索引访问 jQuery 对象(就像您使用 [1] 一样)返回一个没有 animate() 方法的 DOMElement,因此出现错误。

    要执行您需要的操作,您应该改用eq()

    $("span").eq(1).animate({
        opacity: 0.5
    }, 3000);
    

    Updated fiddle

    请注意,索引1 处的项目是第二个span,因为索引是从零开始的。如果您想要第一个跨度,请使用eq(0)

    【讨论】:

    • 作为替代方案,您也可以将allLetters[0] 包装在$() 中,例如:$(allLetters[0])
    • 这是不好的做法,因为它完全是冗余代码。您从 jQuery 对象中获取 DOMElement 只是为了再次将其转换回 jQuery 对象。
    猜你喜欢
    • 2011-03-03
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2012-02-09
    • 2011-04-17
    • 1970-01-01
    • 2019-08-17
    相关资源
    最近更新 更多