有一种方法来设置输入字段值的一部分吗? [英] Is there a way to style part of an input field's value?

查看:125
本文介绍了有一种方法来设置输入字段值的一部分吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用< input> 字段,并且我想将字段的一部分设置为用户以不同颜色打字。例如,假设< input> 有一个样式声明 color:red; 部分 color:blue; 。这是可能的吗?

I'm working with an <input> field and I'd like to style part of the field as the user's typing in a different color. For example, let's say the <input> has a style declaration of color: red; and I want to change part of it to color: blue;. Is there any way this is possible?

如果没有(如我怀疑的),任何创意想法如何可以模拟这种效果,同时仍然保留语义标记,

If there isn't (as I suspect), any creative ideas on how I can simulate this effect while still preserving semantic mark-up?

推荐答案

您的怀疑是正确的:样式将仅应用于整个输入。

Your suspicions are correct: styles will apply to the whole input only.

由于样式只能应用于整个元素,因此解决方案将需要每个所需颜色至少一个元素。

As styles can apply to the entirety of an element only, a solution will require at least one element per required colour.

考虑输入字段相对于用户正在进行的点的改变。输入的三个部分:

Consider the division of the input field with respect to the point at which the user is making changes. There are three sections of the input:


  • 在应用更改的点之前


您无法使用单个输入元素实现此目的。并且由于应用改变的点可以改变,由三个元素包围的输入的部分也将改变。

You cannot achieve this with a single input element. And as the point at which the changes are being applied can change, the portions of the 'input' wrapped by the three elements will also change. JavaScript is required for a solution.

您最初应该包含一个常规输入元素,并放弃所需的颜色。使用JavaScript将输入替换为合适的容器元素。这可以设置为模仿输入元素。

You should initially include a regular input element and forgo any of the required colouring. Use JavaScript to replace the input with a suitable container element. This can be styled to mimic an input element.

随着更改的发生,使用JavaScript来标识上述三个部分。

As changes occur, use JavaScript to identify the above-mentioned three divisions. Wrap them in suitable elements (spans would be ideal) and colour as needed.

考虑以下生成的替换标记的起点:

Consider the following starting point for the generated replacement markup:

<div class="input">
  <span class="nonEdited before">foo</span>
  <span class="edited">fizz</span>
  <span class="nonEdited after">bar</span>
</div>

使用click,keydown和keyup事件来计算输入的三个部分,根据需要伪造输入的三个部分。

Use click, keydown and keyup events to figure out the three divisions for the input and to apply wrap the three portions of the faked input as required.

这篇关于有一种方法来设置输入字段值的一部分吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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