我正在尝试制作一个特定的字母:“*”在我正在使用的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;
}
}
我将如何实现这一目标?
谢谢!
答案 0 :(得分:2)
...因为我真的很无聊,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/
答案 1 :(得分:0)
您只能设置元素的样式,但不能设置属性..
这条线没有任何意义..
this.value == this.getAttribute('*')
* 不是有效的属性名称
这个这里是问题中的当前输入元素。
您可以为输入元素整体设置颜色,但不能为其中的特定字符设置颜色