请解释正确的方式来更新计算的样式,即在CSS文档中设置的样式。document.body.style.background将采用颜色,但不采用渐变。示例如下:
<button onclick="myFunction()">Set background</button>
<script>
function myFunction() {
foo = "#fedcba";
faa = "linear-gradient(45deg, #abcdef, #fedcba);";
document.body.style.background = faa; //foo works, faa doesn't work
}
</script>
我已经尝试了document.body.style.background的许多不同的迭代,并且读到了一些选择器是只读的,而其他选择器可以被操纵的地方。
我现在的代码:已添加注解
来自CSS文件的样式:
body {
background-color: #fedcba;
width: 100%;
height: 100%;
padding: 0;
margin: 0;
font-family: sans-serif;
font-size: 1.2em;
background: -webkit-linear-gradient(315deg, #fedcba, #444);
background: -moz-linear-gradient(315deg, #fedcba, #444);
background: -o-linear-gradient(315deg, #fedcba, #444);
background: -ms-linear-gradient(315deg, #fedcba, #444);
background: linear-gradient(135deg, rgba(10, 100, 0, 100), rgba(200, 200, 200, 100));
background-repeat: no-repeat;
background-attachment: fixed;
}
function setGradient() {
const style = getComputedStyle(body); // reads the CSS for the body style
const background = style.background; //selects the background style
console.info("background: ", background); //writes the style to the console for trouble shooting
var prefix = getCssValuePrefix(); //gets browser prefix -o-, -moz-, -webkit-, -ms-
var orentation = slider; // a number from 0 to 360
var something = prefix + "linear-gradient(" + orentation + "deg, " + color1 + ", " + color2 +")";
//builds a string for the background :: here I have also tried color1.value and color2.value
console.info("setGradient before: ", something); //displays the gradient before being set
document.body.style.background = something; // should set the background to the new gradient
console.info("setGradient after: ", something); //shows that the variables are null
}
// the console returns: setGradient before: -webkit-linear-gradient(nulldeg, null, null)
//Pick and set Bkground colors and orentation
color1.addEventListener("color1", setGradient); //color1 from colorpicker input
color2.addEventListener("color2", setGradient); //color2 from colorpicker input
slider.oninput = setGradient(); //a number from 0-360 step 1 value 180
1条答案
按热度按时间eufgjt7s1#
这只是一个小的拼写错误。您需要删除
;
以使其成为有效的CSS值。