如何将 css 规则应用于 Javascript 表达式

How to apply css rule to a Javascript expression?

本文关键字:应用于 Javascript 表达式 规则 css      更新时间:2023-09-26
$("#confirm_text").text("Are you sure you want " +this.name +" "+ this.type +"?");

整个短语是白色的,但我想 this.name这个.type做橙色。JS方法字体颜色不起作用。有什么办法可以做到这一点吗?

试试这个:

"Are you sure you want <span style='color: orange'>" +this.name +" "+ this.type +"</span> ?"

在这里你可以看到演示:http://jsfiddle.net/2pRzX/

这可能

有效。

"Are you sure you want " +<span class="orange">this.name</span> +" "+ <span class="orange">this.type</span> +"?"

并应用 CSS:

.orange{
    color:orange;
}

在这种情况下,我通常使用< span class="orange"> this.name < /span>
在 css .orange{color:orange;}

您必须将文本放入某种HTML元素中,例如<span>。要么使用 innerHTML ,这是更简单的方法,要么通过逐个创建元素。


使用 jQuery(更新的答案)

随着问题的更新,我更新了我的答案以适应新问题。

代替.text,您可以使用像element.innerHTML =一样工作的.html方法(见下面的旧答案)。它分析 HTML 代码并将其插入到元素中。请注意,应将字符串括在单引号中,以便可以使用双引号而不转义它们。

$("#confirm_text").html('Are you sure you want <span style="color:orange">' + this.name + ' ' + this.type + '?');

使用普通的JavaScript(旧答案)

这个答案已经过时了,因为问题已经改变,需要jQuery而不是普通的JS。我把这个留在这里供以后参考。

内部网页

当您将 HTML 代码添加到 DOM 中的现有元素时,浏览器将解析字符串并创建新元素。您可以在字符串中包含 <span> 标记,浏览器将创建一个元素。

var targetDIV = document.getElementById("targetDIV");
// Add the text with innerHTML
targetDIV.innerHTML = 'Are you sure you want <span style="color:orange;">' + this.name + ' ' + this.type + '</span>?';

创建元素

有时你不能只使用 innerHTML,特别是如果目标元素中已经有文本。这是一个替代方法:

var targetDIV = document.getElementById("targetDIV");
// Append the first peace of text
targetDIV.appendChild(document.createTextNode("Are you sure you want "));
// Create the span element
var orange = document.createElement("span");
// Change its text-color
orange.style.color = "orange";
// Add the text to the span
orange.appendChild(document.createTextNode(this.name + " " + this.type));
// Append the span to the target element
targetDIV.appendChild(orange);
// Append the question mark
targetDIV.appendChild("?");

使用哪个?

在大多数情况下,您可以使用这两种方法之一。不过,我总是使用第二个,因为我觉得它是"更干净"的。您可以更好地控制发生的事情,您可以通过添加/删除/更改行而不是修改大字符串来更改内容。您也不必检查您的 HTML 是否有效。但正如我所说,这两种方法都有效。

试试这个:

"Are you sure you want <span style='color: orange'>" +this.name +" "+ this.type +"</span>?"

您可以在名称和类型值周围添加<span> </span>标签,并使用 CSS 添加颜色。例:http://jsfiddle.net/BAhUG/