Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS-动态添加第二个背景图像_Javascript_Html_Css - Fatal编程技术网

Javascript JS-动态添加第二个背景图像

Javascript JS-动态添加第二个背景图像,javascript,html,css,Javascript,Html,Css,我想创建具有线性渐变的预定义按钮作为背景图像,但在页面本身中,当我通过JS创建按钮时,我想动态地将图片添加到按钮上作为背景 通常,如果我为CSS中的每个按钮添加图像,如下所示: button{ width:96px; height:96px; border-radius:50%; background:radial-gradient(48px 48px,rgba(0,0,255,0),rgba(0,0,255,0) 60%, #00f 70%),url('OK.png'); }

我想创建具有线性渐变的预定义按钮作为背景图像,但在页面本身中,当我通过JS创建按钮时,我想动态地将图片添加到按钮上作为背景

通常,如果我为CSS中的每个按钮添加图像,如下所示:

button{
    width:96px; height:96px; border-radius:50%;
    background:radial-gradient(48px 48px,rgba(0,0,255,0),rgba(0,0,255,0) 60%, #00f 70%),url('OK.png');
}
它会工作的-但是如果我需要这样做,我需要为每个图像创建自定义类,这对我来说不方便,也不像我想要的那样动态。 通过将CSS保留为我想要的模板:

button{
    width:96px; height:96px; border-radius:50%;
    background:radial-gradient(48px 48px,rgba(0,0,255,0),rgba(0,0,255,0) 60%, #00f 70%);
}
在JS中,如果我想将图像动态添加到

ButtonOK.style.backGroundImage="OK.png"; 
它将覆盖明显的渐变。 我无法将CSS代码复制到JS中,因为我想将其保留在那里,以防我的一个用户更改CSS中的渐变颜色-我的JS文件需要为此更改做好准备

我建议:

styleSheets[0].cssRules[ToFindTheRuleIndex].style.backgroundImage+",url('"+GivenImage+"');"
但是,通过这种方式,我需要假设CSS中指定的用户是background image属性,并且使用的样式表是0中唯一的默认样式表,或者即使是其他自定义CSS文件,默认样式表仍然是第一个。需要让JS函数太长太复杂

问题是: 如何将JS中的图像添加到线性渐变的顶部,使其与我的第一个示例类似? 请求纯JS解决方案

非常感谢:

如果您愿意使用背景图像而不是背景图像,则可以使用正则表达式替换来删除现有图像URL,并将其替换为新的图像URL

下面的方法使用getComputedStyle,以便从CSS中提取背景,只替换最后的图像

函数replaceBackgroundImageelement,newImage{ var bg=getComputedStyleelement.getPropertyValuebackground-image; bg=`${bg.replace/,url\.\/g,},url'${newImage}`; element.style.backgroundImage=bg; } var ButtonOK=document.getElementByIdok; replaceBackgroundImageButtonOK,MyNewImage.png; console.logButtonOK.style.backgroundImage; replaceBackgroundImageButtonOK,AnotherImage.png; console.logButtonOK.style.backgroundImage; 嗯{ 填充:40px; 背景图像:径向梯度48px 48px,rgba0,0,255,0,rgba0,0,255,0,60%,00f 70%; }
好的,你试过ButtonOK.style.background=radial-gradient48px 48px,rgba0,0255,0,60%,00f 70%,url'OK.png'?我想这应该行得通。我提到:我不想将数据复制到JS,所以它保留在CSS渐变中,用户可以更改颜色,或者选择其他颜色,可能是纯色作为主要背景