gpt4 book ai didi

Javascript - 将CSS样式添加到带有类的元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:47:48 25 4
gpt4 key购买 nike

我只想在 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: 'undefined' is not an object (evaluating 'productAttr.style.top = "-90px"')

如果我想更改其他样式 f.e.不透明度或颜色,我遇到了同样的问题。

我该如何解决这个问题?

在此先感谢您的帮助。

最佳答案

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

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

关于Javascript - 将CSS样式添加到带有类的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35433575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com