如何只允许文本框中的某些文本为只读,同时允许编辑其余文本 [英] How to make only some text in a text-box read-only while allowing the rest to be edited

查看:127
本文介绍了如何只允许文本框中的某些文本为只读,同时允许编辑其余文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Javascript在文本框的开头创建一个包含一些只读文本的文本框,然后允许在只读文本后面进行编辑。我怎么能在Javascript / jquery中做到这一点?

I'm trying to use Javascript to make a text box that contains some read-only text at the beginning of the text box and then allows editing following the read-only text. How can I do this in Javascript/jquery?

推荐答案

这是一次尝试:

var readOnlyLength = $('#field').val().length;

$('#output').text(readOnlyLength);

$('#field').on('keypress, keydown', function(event) {
  var $field = $(this);
  $('#output').text(event.which + '-' + this.selectionStart);
  if ((event.which != 37 && (event.which != 39)) &&
    ((this.selectionStart < readOnlyLength) ||
      ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
    return false;
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="field" type="text" value="CAN'T TOUCH THIS!" size="50" />
<div id="output">
</div>

这将禁用只读部分的左右箭头以外的键。它还会在只读部分的末尾禁用退格键。

This disables keys other than the left and right arrows for the read-only part. It also disables the backspace key when just at the end of the read-only part.

从我读过的内容来看,这不适用于IE< = 8。

From what I've read, this won't work on IE <= 8.

这里是普通的JavaScript(没有JQuery):

Here it is in plain JavaScript (no JQuery):

function makeInitialTextReadOnly(input) {
  var readOnlyLength = input.value.length;
  field.addEventListener('keydown', function(event) {
    var which = event.which;
    if (((which == 8) && (input.selectionStart <= readOnlyLength)) ||
      ((which == 46) && (input.selectionStart < readOnlyLength))) {
      event.preventDefault();
    }
  });
  field.addEventListener('keypress', function(event) {
    var which = event.which;
    if ((event.which != 0) && (input.selectionStart < readOnlyLength)) {
      event.preventDefault();
    }
  });
}

makeInitialTextReadOnly(document.getElementById('field'));

<input id="field" type="text" value="CAN'T TOUCH THIS!" size="50" />

这篇关于如何只允许文本框中的某些文本为只读,同时允许编辑其余文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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