有没有办法在标签中设置部分文本的样式 - 更改颜色、粗体、大小等?
问问题
353 次
2 回答
3
使用 HTML 小部件而不是标签。然后:
HTML label = new HTML();
label.setHtml("Brown <span class=\"brown\">fox</span>");
于 2012-12-30T13:22:44.287 回答
-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'
});
这肯定可以与一些错误捕获有关(例如,如果将数组传递给小于或大于两个元素的函数,则没有任何反应,并且没有错误返回给用户/开发人员;如果el
变量既不是一个节点引用或一个id
,事情出错了:)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;
}
参考:
于 2012-12-31T01:17:19.457 回答