简体   繁体   English

Javascript文本框突出显示问题

[英]Javascript textbox highlight question

I've got a textbox, and I want to select a substring programatically. 我有一个文本框,我想以编程方式选择一个子字符串。 Is there an easy way to do this? 是否有捷径可寻?

To highlight the selected text in the textbox, you can use this javascript snippet: 要突出显示文本框中的选定文本,可以使用以下javascript代码段:

var textbox = document.getElementById("mytextbox");
if (textbox.createTextRange) {
    var oRange = this.textbox.createTextRange(); 
    oRange.moveStart("character", start); 
    oRange.moveEnd("character", length - this.textbox.value.length); 
    oRange.select();
} else if (this.textbox.setSelectionRange) {
    textbox.setSelectionRange(start, length);
}

textbox.focus();

In this snippet, mytextbox is the id the input textbox and start and length represent your substring parameters. 在此代码段中,mytextbox是输入文本框的ID,而start和length表示您的子字符串参数。

My JS is a little rusty, but something along the lines of: 我的JS有点生锈,但是有些类似:

document.getElementById("foo").value.substring(start, end);

should get you started. 应该让您开始。

And, I'm assuming that you're referring to a <textarea> . 而且,我假设您指的是<textarea>

<input type="text" id="textbox" value="sometextintextbox" />

<script type="text/javascript">
var textboxvalue=document.getElementById("textbox").value;
alert(textboxvalue.substring(3,7));
</script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM