javascript - 如何使用 javascript 设置 backgroundImage
问题描述
function myFunction2() {
for (let i=1; i < 3; i++){
if (i<2){
var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
var hex1 = '#' + numhex.slice(0, 6);
// return hex1;
// console.log(hex1);
}
else {
var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
var hex2 = '#' + numhex.slice(0, 6);
// return hex2;
// console.log(hex2);
}
}
// document.getElementById("container").style.backgroundImage = "linear-gradient(to right, " + {hex1} + ", " + {hex2} + ")";
document.getElementById("container").setProperty("background-image", "linear-gradient(to right, " + {hex1} + ", " + {hex2});
document.getElementById("description").innerHTML = "The code of the color is: linear-gradient( 270deg, " + hex1 + ", " + hex2 + " );";
};
您好,我正在尝试将线性渐变的两种颜色设置为特定元素的背景图像属性中的参数,但我的 setProperty 似乎有问题。除了这行代码,一切都运行良好。 我也试过 style.backgroundImage 没有结果。 我是 js 新手。 提前致谢
解决方案
首先,这里有一个提示:永远不要使用 'var',而是使用 'let'。JS中没有setProperty()
函数,需要使用element.style["style you want to change"] = "what you want to change it to"
. 并且,您不应该将变量包装在 '{}' 中,否则它们将成为非变量,因此代码应为:
function myFunction2() {
for (let i=1; i < 3; i++){
if (i<2){
var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
var hex1 = '#' + numhex.slice(0, 6);
// return hex1;
// console.log(hex1);
}
else {
var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
var hex2 = '#' + numhex.slice(0, 6);
// return hex2;
// console.log(hex2);
}
}
document.getElementById("container").style["background-image"] = "linear-gradient(to right, " + hex1 + ", " + hex2 + ")";
document.getElementById("description").innerHTML = "The code of the color is: linear-gradient( 270deg, " + hex1 + ", " + hex2 + " );";
};
此外,如果您使用的是 div,则还必须定义高度。
推荐阅读
- android - 在 TextView Kotlin 中的 OCR 文本提取上搜索和可点击文本
- spring-cloud-config-server - 如何在不使用 spring.cloud.config.server.git.refreshRate 属性的情况下以编程方式从 spring 云配置服务器中的 git repo 中提取代码?
- splunk - 给定时间段内所有事件的数值总和
- javascript - 货币符号的 JavaScript Concat 问题
- binary-tree - Avl 树查找与插入
- reactjs - 用 Draft.js 实体替换特定字符串
- mmenu - 使用 mmenu 进行性能调试 - 如何构建非缩小、非混淆版本
- php - 路线:product.details URI:product/{slug} Laravel 中缺少参数:slug] 错误
- c# - 隔离模式下的 Azure 函数:如何构建 Docker 容器?
- string - 如何在 nginx 中拆分字符串?