【问题标题】:How can I change color with append Div?如何使用附加 Div 更改颜色?
【发布时间】:2021-01-13 23:16:30
【问题描述】:

我无法通过附加 div 动态更改颜色。我想更改 div 的默认颜色,红色。

我的 HTML 标记是:

<div id="risultato"></div>

Javascript 代码:

var result= document.getElementById('risultato');
result.style.color = "red";
result.innerHTML+= <a href="www.google.com">

但 google.com 的颜色是蓝色而不是红色。

我也尝试过使用 css:

<style>
#risultato {
    margin-left: 18px;
    font-size: 17px;
    text-decoration: none;
    color: red;
}   
</style>

但它不起作用。我该怎么做?

【问题讨论】:

  • 几个问题。 &lt;a href="www.google.com"&gt; 需要用引号引起来。此外,它需要结束 &lt;/a&gt; 标记以及一些内容。例如。 result.innerHTML+= '&lt;a href="www.google.com"&gt;Google&lt;/a&gt;'。但除此之外,链接具有您需要覆盖的默认样式
  • 简短的回答是CSS Specificity。稍长的版本是 a 标签有自己的默认样式,您需要覆盖。

标签: javascript css innerhtml


【解决方案1】:

var result= document.getElementById('risultato');
result.style.color = "red";
result.innerHTML+= '<a style="color:green" href="www.google.com">google</a>'
both js and css are basically fine.  your innerHTML statement needs some fine tuning.
&lt;div id="risultato"&gt;some text&lt;/div&gt;

【讨论】:

    【解决方案2】:

    尝试:

    <style>
    #risultato a {
    color:red;
    }   
    </style>
    

    【讨论】:

      【解决方案3】:

      // Get the div
      var result = document.getElementById('risultato');
      // Append the element to the div and give it a class
      result.innerHTML += "<a class='link' href='www.google.com'>Google</a>";
      // Get the element (link)
      let resultLink = document.querySelector('#risultato a');
      // Style it
      resultLink.style.color = 'red';
      #risultato a{
        font-size:17px;
      }
      &lt;div id="risultato"&gt;&lt;/div&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-24
        • 1970-01-01
        • 2018-02-10
        • 1970-01-01
        • 2019-02-19
        • 2018-10-01
        • 2014-09-15
        • 1970-01-01
        相关资源
        最近更新 更多