我正在尝试将一个特定的字母:“*”在我正在使用的 JavaScript 代码行中显示为红色。 以下是我的原创:
function init(){
var inp = document.getElementsByTagName('input');
for(var i = 0; i < inp.length; i++) {
if(inp[i].type == 'text','tel','number', 'email') {
inp[i].setAttribute('rel',inp[i].defaultValue)
inp[i].setAttribute('style', 'color: grey;')
inp[i].onfocus = function() {
if(this.value == this.getAttribute('rel')) {
this.value = '';
this.setAttribute('style', 'color: black;')
} else {
return false;
}
}
为了使特定字母变为红色,我会将其更改为吗?
function init(){
var inp = document.getElementsByTagName('input');
for(var i = 0; i < inp.length; i++) {
if(inp[i].type == 'text','tel','number', 'email') {
inp[i].setAttribute('rel',inp[i].defaultValue)
inp[i].setAttribute('style', 'color: grey;')
inp[i].onfocus = function() {
if(this.value == this.getAttribute('rel')) {
this.value = '';
this.setAttribute('style', 'color: black;')
if(this.value == this.getAttribute('*')) {
this.setAttribute('style', 'color: red;')
} else {
return false;
}
}
我如何实现这一目标?
最佳答案
...因为我真的很无聊,I ended up doing what you wanted using javascript .
它使用 Mootools,但如果您愿意,它应该为您提供足够的灵感来使用 jQuery 重新创建它。
function reposition() {
var position = inputEl.getPosition();
var occludeLabel = inputEl.value;
occludeLabel = occludeLabel.replace(/\*/g, '<span class="red">*</span>', 'g');
occludeEl.setStyles({
top: position.y + 1,
left: position.x + 1
});
occludeEl.set('html', occludeLabel);
}
基本上,每次模糊输入时,都会将包含输入框值的 div 放置在输入框上方,遮挡文本。我运行了一个简单的 .replace()
将所有星号替换为跨度,这会将其内容变成红色。
请参阅此 jsfiddle 了解所有代码:http://jsfiddle.net/eTEvQ/2/
关于JavaScript 使特定字母具有不同的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13213649/