Mad*_*iha 5 html javascript css css3
我想以编程方式向元素添加渐变背景.
使用适当的CSS,就像这样
background: -moz-linear-gradient(top, #000000 0%, #ffffff 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#000000), color-stop(100%,#ffffff)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #000000 0%,#ffffff 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #000000 0%,#ffffff 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #000000 0%,#ffffff 100%); /* IE10+ */
background: linear-gradient(to bottom, #000000 0%,#ffffff 100%); /* W3C */
Run Code Online (Sandbox Code Playgroud)
现在,我想用JavaScript来做.所以我想到了这样的事情:
gradientList.forEach(gradient => el.style.background = gradient)
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用.每次都会覆盖background属性,并且只应用列表中的最后一个渐变.
对于大多数其他属性,供应商之间的属性名称是不同的,linear-gradient但是,它们都是background.
现在,我知道我可以在元素中添加一个类名并附加一个style节点document.head(这就是我现在正在做的事情),但它非常hackish,而且我想要一个更好的DOM做事方式.
简而言之,如何使用vanilla JavaScript将供应商前缀渐变添加到DOM元素?
假设您不想通过库,简单的方法是检测浏览器,然后执行以下操作:
el.style.background = browserPrefix + gradient;
Run Code Online (Sandbox Code Playgroud)
一般来说,无前缀库还规范了梯度的其他一些东西,所以我强烈推荐它。