[英]Unable to set div's background to linear gradient using Javascript
I'm trying to make a dynamic div
element with styles including linear gradient.我正在尝试使用 styles 制作一个动态div
元素,包括线性渐变。 It should be displayed dynamically with a button, but the gradient does not get added.它应该使用按钮动态显示,但不会添加渐变。
var x = document.getElementById("btn"); x.addEventListener("click", addbox); function addbox() { var y = document.createElement("Div"); y.id = "div1"; y.style.border = "1px"; y.style.borderRadius = "20px"; y.style.height = "200px"; y.style.width = "500px"; y.style.backgroundImage = "linearGradient(to bottom right, yellow, cyan)"; document.getElementsByTagName("body")[0].appendChild(y); }
#btn { height: 50px; width: 150px; }
<button id="btn" onclick="addbox()"> CLICK ME TO DISPLAY </button>
Your code has a lot of little mistakes but here is something that works:您的代码有很多小错误,但这是可行的:
<!doctype html>
<html>
<head>
<title> ADD BOX ON CLICK FUNCTION </title>
<style>
#btn {
height: 50px;
width: 150px;
}
</style>
</head>
<body>
<script>
function addbox() {
var y = document.createElement("Div");
y.id = "div1";
y.style.border = "1px";
y.style.borderRadius = "20px";
y.style.height = "200px";
y.style.width = "500px";
y.style.background = "linear-gradient(to bottom right, yellow , cyan)";
document.getElementsByTagName("body")[0].appendChild(y);
}
window.addEventListener("DOMContentLoaded", (event) => {
var x = document.getElementById("btn");
x.addEventListener("click", addbox);
});
</script>
<button id="btn"> CLICK ME TO DISPLAY </button>
</body>
</html>
Your document.getElementById("btn")
cannot work before the page has finished loading, so you have to put this inside a window.addEventListener("DOMContentLoaded")
event that will fire only when your div is there您的document.getElementById("btn")
在页面完成加载之前无法工作,因此您必须将其放在window.addEventListener("DOMContentLoaded")
事件中,该事件仅在您的 div 存在时触发
Remove the onclick="addbox()"
from the div because it would fire twice per click从 div 中删除onclick="addbox()"
因为每次点击它会触发两次
linearGradient
spelling is wrong. linearGradient
拼写错误。 It's linear-gradient
它是linear-gradient
的
The property to apply the linear gradient is not y.style.backgroundImage
but y.style.background
应用线性渐变的属性不是y.style.backgroundImage
而是y.style.background
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.