【问题标题】:JavaScript get Elements By Class Name [duplicate]JavaScript按类名获取元素[重复]
【发布时间】:2014-12-18 01:20:25
【问题描述】:

为什么我的 getElementsByClassName 代码不起作用?它在使用 getElementById 但不适用于类时有效?我正在使用 TweenLite 扩展。

我的代码不起作用-http://codepen.io/bleubateau/pen/pvbeaO 与 ID 相同的代码-http://codepen.io/bleubateau/pen/ogLZqb 与该类一起使用的类似代码-http://codepen.io/bleubateau/pen/PwzpQj

window.onload = function() {
  var play = document.getElementById("lay");

play.onmouseover = function(){
    TweenMax.to(play, 0.5, {width:"120px", marginLeft:"-60px", marginTop:"-60px", repeat:-1, repeatDelay:0.1, yoyo:true});

};

play.onmouseout = function(){
    TweenLite.to(playBTN, 1, {width:"100px", marginLeft:"-50px", marginTop:"-50px"});
};
}

【问题讨论】:

  • 请记住,当使用类名时,它会返回一个数组,即使它是单个对象...document.getElementById("lay")[0]
  • 在没有看到您的 HTML 的情况下无法提供帮助 - 请将其包含在您的问题中。
  • 最好使用 document.querySelectorAll('.lay')[0],因为它比 getElementsByClassName 得到更广泛的支持。
  • 如果只需要第一个,那么.querySelector(".lay")

标签: javascript html css gsap


【解决方案1】:

getElementsByClassName() 生成一个节点列表,因此即使您的列表只包含一项,您仍然需要像这样访问它:

var play = document.getElementsByClassName('lay')[0];

【讨论】:

  • Nit:它创建一个 NodeList,而不是一个数组。
  • @FelixKling — 不是真的挑剔,NodeList 是实时的,所以可能会有一些意想不到的行为。 ;-)
猜你喜欢
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多