使用Javascript无法更改线性梯度

时间:2019-05-19 18:21:21

标签: javascript html css

我正在尝试在项目中使用JavaScript更改线性渐变。我的问题是在运行代码后什么也没有发生。如果我尝试直接在CSS类容器中使用线性渐变字符串,则一切正常,但无法通过JavaScript进行更改。这是我要运行的代码:

function init() {
    var Lohn = "undefined";
    var Datum = "undefined";
    var Pausenstueck = "undefined";
    var Zakstueck = "undefined";
    var Ueberstundenstueck = "undefined";
    var StundeKoord = "undefined";
    var Tagesdauer = "undefined";

    let UebersichtTemplate = document.createElement("dd");
    let UebersichtDD = document.getElementById("Uebersicht_Window_child");

    UebersichtTemplate.innerHTML = "<span class='textRight'>" + Lohn + "</span><span class='text'>" + Datum + "</span>";

    let a = document.importNode( UebersichtTemplate,true);
a.classList.add("percentage", "percentage-" + Math.round(StundeKoord*Tagesdauer));
    let colorString = "linear-gradient(to right,  #9c9e9f 0%,#9c9e9f " + Pausenstueck + Zakstueck + Ueberstundenstueck + " 100%);"
	UebersichtDD.appendChild(a);

    a.style.backgroundImage = '-webkit-linear-gradient(to right,  #9c9e9f 0%,#9c9e9f 50%, #F53323 50%, #F53323 100%)';
}

document.addEventListener("DOMContentLoaded", init);
<body>
  <div id="Uebersicht_Window_child"></div>
 </body>

我已经尝试使用双引号而不是单引号,但是它也不起作用。离开“ -webkit-”也不能解决我的问题...我绝对不知道问题所在。希望你们能帮助我:)

谢谢!

1 个答案:

答案 0 :(得分:0)

有一个主要问题:您实际上从未插入导入到文档中的dd元素:

来自Document​.import​Node()

  

Document对象的importNode()方法创建Node的副本或   来自另一个文档的DocumentFragment,要插入到   当前文档

(强调我的)

还有其他一些问题,主要涉及代码结构和样式-但它们可能与核心问题不相关-但还有可能与创建colorString有关的语法问题。

function init() {
    var Lohn        = "undefined";
    var Datum       = "undefined";
    var StundeKoord = "undefined";
    var Tagesdauer  = "undefined";
    // -----------------------------
    var Pausenstueck       = "#9c9e9f 50%";
    var Zakstueck          = "#F53323 50%";
    var Ueberstundenstueck = "#F53323 100%";

    let UebersichtTemplate = document.createElement("dd");
    UebersichtTemplate.innerHTML = "<span class='textRight'>" + Lohn + "</span>" +
                                   "<span class='text'>" + Datum + "</span>";
    let a = document.importNode( UebersichtTemplate, true );
    a.classList.add( "percentage", "percentage-" + Math.round(StundeKoord*Tagesdauer) );
    a.style.backgroundImage = `-webkit-linear-gradient(top right, #9c9e9f 0%, ${Pausenstueck}, ${Zakstueck}, ${Ueberstundenstueck} )`;
    // insert the imported node.
    document.body.appendChild(a);
}

document.addEventListener("DOMContentLoaded", init);
<body>
  <div id="Uebersicht_Window_child"></div>
 </body>