JavaScript - 给具有特定类的元素添加CSS样式

7

我希望在JS中添加一个CSS样式,但是我不想为了这一个小事情而引入jQuery。

我的代码:

document.addEventListener('DOMContentLoaded', function() {
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
        var productAttr = document.getElementsByClassName('product-attributes');
        productAttr.style.top = "-90px";
    }
});

控制台中的错误是:

TypeError:“未定义”不是对象(评估“productAttr.style.top =“-90px””)

如果我想改变其他样式,例如透明度或颜色,我会遇到同样的问题。

我该怎么解决?

提前感谢您的帮助。


可能是如何使用JavaScript更改CSS属性的重复问题。 - 8eecf0d2
1
getElementsByClassName 返回匹配元素的集合,而不是单个对象。 - DanielS
4个回答

4

您需要循环遍历结果,因为getElementsByClassName()返回一个元素集合:

for(var i = 0; i < productAttr.length; i++)
{
    productAttr[i].style.top = "-90px";
}

0
也许是因为在CSS中无法给出负值

top:"-90px" === bottom "90px"

也许现在可以正常工作了

document.addEventListener('DOMContentLoaded', function() {
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
        var productAttr = document.getElementsByClassName('product-attributes');
        productAttr.style.bottom = "90px";
    }
});

-1
最好为目标元素分配一个id,然后使用getElementById()进行定位,因为不能有相同id的元素,因此如果存在多个具有相同className的元素,则getElementByClassName()将返回一个数组。如果您需要定位多个元素,则应该通过for循环遍历它们,并在循环到的第n个项目上应用更改:
for(x = 0; x < array.length; x++){
    array[x].style.top = '-90px';
}

温馨提示:还需注意添加 position: relative|absolute|fixed 以确保 'top' 属性可用。
感谢 Sebastien Daniel 的编辑。

1
当使用 getElementsByClassName() 函数时,你得到的是一个集合(即类似于数组的结构)。你上面的代码将会出现错误,因为 HTML 集合并没有 style 属性。此外,使用 style 属性来设置样式不被建议,你应该使用 element.setAttribute("style", "value"); - Sebastien Daniel
那么最好将元素更改为具有ID,然后通过ID定位元素? - zehata
不一定,这完全取决于您的用例。如果您的目标是唯一的,那么使用#id和getElementById()更可取。然而,如果您有多个需要调整的元素(例如共享className),那么使用getElementsByClassName()将允许您抓取它们并使用这些元素需要经过的任何过程进行迭代。 - Sebastien Daniel
好的,谢谢。我改成了使用id而不是class,现在它可以正常工作了。谢谢。 - Robson

-1
当选择一个类时,您必须指示编号作为标签,这不像ID一样只有一个。
它可能是以下代码之一,具体取决于您要应用哪个类:
document.addEventListener('DOMContentLoaded', function() {
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
        var productAttr = document.getElementsByClassName('product-attributes');
        productAttr[0].style.top = "-90px";
        productAttr[1].style.top = "-90px";
        productAttr[2].style.top = "-90px";
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接