如何更改输入文本每个字符的样式 [英] How to change style of each character of input text

查看:40
本文介绍了如何更改输入文本每个字符的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我想随机更改文本每个字符的CSS.就像我输入 Stack 一样,我将在输入字段的底部得到红色的S,蓝色的t,绿色的...等等.

Here I want to randomly change the CSS of each character of text. Like if I input Stack I will get S in red, t in blue, a in green... etc on the bottom of the input field.

var myModel = {
	name: "Mayur",
};

var myViewModel = new Vue({
	el: '#my_view',
	data: myModel
});

span{
color:green;
font-weight:600;
font-size:20px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>

<div id="my_view">
  <label for="name">Enter name:</label>
  <input type="text" v-model="name" id="name" name="name" />
  <p>Welcome, <span>{{ name | uppercase }}</span></p>
</div>

推荐答案

我没有使用Vue,也不熟悉其内部事件和流程,但这是我用普通的 JavaScript制作的一个小原型.:

I haven't worked with Vue and I'm not familiar with its internal events and processes, but here's a tiny prototype i made in plain JavaScript:

document.querySelector('button').onclick = function (){
    let span = document.querySelector('span.letters'),
        text = span.textContent;
    span.innerHTML = '';
    Array.from(text).map(function(l){
        let color = document.createElement('span');
        color.innerHTML = l;
        color.style.color = 'rgb(' +
            randInterval(0, 255) + ',' +
            randInterval(0, 255) + ',' +
            randInterval(0, 255) + ')';
        span.appendChild(color);
    });
}

function randInterval(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

<div><span class="letters">STACK</span></div>

<button>Random colors</button>

我有意将将 rgb()的每个值随机化的函数放置在函数中,因此您可以轻松更改它(现在的颜色确实是随机的).如果要调暗,则需要降低 max 值.如果要使颜色更浅,则需要增加 min s.

I've purposefully placed the function that randomizes each value of rgb() in a function, so you can alter it easily (now the colors are trully random). If you want to make the darker, you need to lower the max values. If you want the colors lighter, you need to increase the mins.

这篇关于如何更改输入文本每个字符的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆