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

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

问题描述

我正在处理一个 <input> 字段,我想在用户输入不同颜色时为该字段的一部分设置样式.例如,假设 有一个 color: red; 的样式声明,我想将它的 part 更改为 <代码>颜色:蓝色;.有什么办法可以做到吗?

如果没有(正如我怀疑的那样),关于如何模拟这种效果同时仍然保留语义标记的任何创意?

解决方案

您的怀疑是正确的:样式仅适用于整个输入.

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

考虑相对于用户进行更改的点对输入字段的划分.输入分为三个部分:

  • 在应用更改之前
  • 在应用更改之后
  • 此时正在应用更改

您无法使用单个输入元素实现此目的.随着应用更改的点可能发生变化,由三个元素包裹的输入"部分也将发生变化.解决方案需要 JavaScript.

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

随着发生变化,使用 JavaScript 来识别上述三个部门.根据需要将它们包裹在合适的元素中(跨度是理想的)和颜色.

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

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

使用 click、keydown 和 keyup 事件找出输入的三个部分,并根据需要对伪造输入的三个部分应用包装.

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:

  • that before the point at which changes are being applied
  • that after the point at which changes are being applied
  • that at the point the changes are being applied

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.

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.

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>

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天全站免登陆