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

标签 javascript

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

相关文章:

javascript - HTML/JS Canvas 在对象之间绘制线

javascript - 从 ng-click 调用指令内的绑定(bind)函数

javascript - hasClass 和条件不工作

javascript - 当组件可以随时卸载时,如何使用 React 管理 useEffect 中的竞争条件风险?

javascript - 当窗口调整大小标签 div 不能满窗口时

javascript - 无法在 JavaScript 中使用我的 php 变量

javascript - 条件循环可以根据其他值改变

javascript - moment.js 如何确定区域设置

javascript - 如何从外部文件运行函数作为表单的 Action ?

javascript - 在 Swagger 中支持复杂对象