【问题标题】:Is it possible to style some part of text in innerHtmlin JavaScript?是否可以在 innerHtmlin JavaScript 中设置部分文本的样式?
【发布时间】:2020-06-14 08:47:31
【问题描述】:

我想在将段落的某些部分附加到 html 页面之前对其进行样式设置。我尝试了一些方法,但它们不起作用。请参阅注释语法。我想设置Description这个词的样式,这样做的正确方法是什么?谢谢。

const detailsDiv = document.getElementById("details");
var articleDecs = document.createElement("p");
articleDecs.setAttribute("class", "productDesc");
var str = "Description:  ";
//var str2 = str.bold();
//var str3 = "<b>Description:  </b>" ;
articleDecs.innerText = "Description: " +catalogArray[pos].desc;

//articleDecs.innerText = str2  +catalogArray[pos].desc;
//articleDecs.innerText = str3 "+catalogArray[pos].desc;
console.log(articleDecs);
detailsDiv.appendChild(articleDecs);
&lt;div id="details"&gt;&lt;/div&gt;

【问题讨论】:

  • 我编辑了您的 sn-p 并修复了控制台错误 var str3 = "&lt;b&gt;Description: &lt;/b" &gt; ; 无效
  • 你想要什么风格?创建的 p 标签?

标签: javascript html css innerhtml


【解决方案1】:

如果你正确连接并使用innerHTML,它就可以工作

const catalogArray = [{
  desc: "Desc 1"
}]

let pos = 0

const detailsDiv = document.getElementById("details");
var articleDecs = document.createElement("p");
articleDecs.setAttribute("class", "productDesc");
var str1 = "Description:  ".bold();
articleDecs.innerHTML = str1 + catalogArray[pos].desc;
console.log(articleDecs);
detailsDiv.appendChild(articleDecs);
&lt;div id="details"&gt;&lt;/div&gt;

但是为什么不使用 CSS 而不是 .bold()

const catalogArray = [{
  desc: "Desc 1"
}]

let pos = 0

const detailsDiv = document.getElementById("details");
var articleDecs = document.createElement("span");
articleDecs.setAttribute("class", "productDesc");
articleDecs.innerText = "Description:  ";
detailsDiv.appendChild(articleDecs);
detailsDiv.appendChild(document.createTextNode(catalogArray[pos].desc));
.productDesc { font-weight:bold }
&lt;div id="details"&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    如果你想使用 js 来做样式,那就是它:

    var catalogArray = [{
        desc: "Desc 1"
    }]
    
    var pos = 0;
    
    const detailsDiv = document.getElementById("details");
    var articleDecs = document.createElement("p");
    articleDecs.setAttribute("class", "productDesc");
    articleDecs.innerHTML = "Description:" + catalogArray[pos].desc;
    articleDecs.style.fontWeight = "bold";
    detailsDiv.appendChild(articleDecs);
    &lt;div id="details"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多