我正在寻找一个javascript语言代码示例,当您在任何网站的任何textarea中编写文本并按下输入时,会自动生成两个输入(两个中断)。
例如
扩展名已关闭(默认)
Hello world 1
<br>
Hello world 2
扩展程序已开启
Hello world 1
<br>
<br>
Hello world 2
答案 0 :(得分:-1)
以下是此http://jsfiddle.net/5om3ahcz/1/ 已更新
功能:
function doubleCarriage(id){
var a = document.getElementById(id); // grab the element
a.addEventListener('keypress',function(e){ //create the event listener
if(e.which == 13 || e.keyCode == 13 ) { // e.which || e.keyCode is enter
e.preventDefault(); //prevent Default action from performing
var caret = getCaret(a); //get our carets Position
var length = a.value.length; //get the length of the value
a.value = a.value.substring(0, caret) //gets our first half of string
+ "\n\n" + //enters two breaks
a.value.substring(caret, length); // gets the second half of our string.
}
});
}
function getCaret(el) {
/*
Tells us where the caret position is
found at
http://stackoverflow.com/questions/263743/caret-position-in-textarea-in-characters-from-the-start#answer-263796
*/
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null)
return 0;
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
//run the code like so
doubleCarriage("textarea");
尝试小提琴,看看这是否能达到你想要的效果。