有没有办法在标签中设置部分文字的样式 - 更改颜色,粗体,大小等?
答案 0 :(得分:3)
使用HTML小部件而不是Label。然后:
HTML label = new HTML();
label.setHtml("Brown <span class=\"brown\">fox</span>");
答案 1 :(得分:-1)
我有点无聊,我想我可以提供一些有用的东西,所以说,我提供这个:
function elemStyle(el, needle, settings) {
// if there's no 'el' or 'needle' arguments, we quit here
if (!el || !needle) {
return false;
}
else {
// if 'el' has a nodeType of 1, then it's an element node, and we can use that,
// otherwise we assume it's the id of an element, and search for that
el = el.nodeType == 1 ? el : document.getElementById(el);
// if we have a 'settings' argument and it's an object we use that,
// otherwise we create, and use, an empty object
settings = settings && typeof settings === 'object' ? settings : {};
// defining the defaults
var defaults = {
'class': 'presentation',
'elementType': 'span'
},
// get the text from the 'el':
haystack = el.textContent || el.innerText;
// iterate over the (non-prototypal) properties of the defaults
for (var prop in defaults) {
if (defaults.hasOwnProperty(prop)) {
// if the 'settings' object has that property set
// we use that, otherwise we assign the default value:
settings[prop] = settings[prop] || defaults[prop];
}
}
// defining the opening, and closing, tags (since we're using HTML
// as a string:
var open = '<' + settings.elementType + ' class="' + settings.class + '">',
close = '</' + settings.elementType + '>';
// if 'needle' is an array (which is also an object in JavaScript)
// *and* it has a length of 2 (a start, and stop, point):
if (typeof needle === 'object' && needle.length === 2) {
var start = needle[0],
stop = needle[1];
el.innerHTML = haystack.substring(0, start) + open + haystack.substring(start, stop) + close + haystack.substring(stop);
}
// otherwise if it's a string we use regular expressions:
else if (typeof needle === 'string') {
var reg = new RegExp('(' + needle + ')');
el.innerHTML = haystack.replace(reg, open + '$1' + close);
}
}
}
上面这样称呼:
// a node-reference, and a string:
elemStyle(document.getElementsByTagName('label')[0], 'Input');
// a node-reference, and a start-stop array:
elemStyle(document.getElementsByTagName('label')[0], [6, 8]);
// an id (as a string), and a string to find, with settings:
elemStyle('label1', 'Input', {
'elementType' : 'em'
});
这肯定可以解决一些错误(例如,如果一个数组被传递到比两个元素nothing happens更少或更多的函数中,并且没有错误返回给用户/开发人员;如果el
变量既不是节点引用,也不是id
,things go wrong: Uncaught TypeError: Cannot read property 'textContent' of null
)。
话虽如此,我觉得很脏,所以我添加了一个简单的错误检查,并报告,如果el
没有解析为文档中的实际节点:
el = el.nodeType == 1 ? el : document.getElementById(el);
// if 'el' is null, and therefore has no value we report the error to the console
// and then quit
if (el === null) {
console.log("You need to pass in either an 'id' or a node-reference, using 'document.getElementById(\"elemID\")' or 'document.getElementsByTagName(\"elemTag\")[0].");
return false;
}
参考文献: