JavaScript 使特定字母具有不同的颜色?

标签 javascript jquery

我正在尝试将一个特定的字母:“*”在我正在使用的 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/

相关文章:

javascript - 如何提交表单然后重定向到个性化感谢页面?

javascript - Google Maps API for JavaScript 在 StageWebView 中的 AIR Android 项目中使用时无法正常工作?

javascript - 如何在按下回车键时显示警报

javascript - 如何在鼠标向下滚动时使 div 滚动速度比 html 的其余部分更快?

javascript - 日期范围选择器为 24 小时范围创建错误的时间值

javascript - 在特定元素上禁用移动长按上下文菜单

javascript - ng-Directive 在 ng-Controller 之前被调用以将数据绑定(bind)到 HTML

javascript - meteor JS : RegisterHelper to display associated user information

javascript - 验证的淡入动画- Angular

jquery - 如何使用jquery删除字符串中的字符串的一部分