我只想在 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/