当我在 textarea 中选择一个文本并按Ctrl+i我想在它前面加上 HTML。因此,如果我dolor sit
在里面选择,Lorem ipsum dolor sit amet
我希望该文本变为Lorem ipsum <em>dolor sit</em> amet
. 与我们在 WordPress 中可以实现的功能相同。
https://codepen.io/ivan-topi/pen/dybXzvd
jQuery('textarea').on('keydown', function(e) {
// If key press combination is CTRL+i
if (e.ctrlKey && e.key == 'i') {
// Get selected text
var selectedText = window.getSelection().toString();
// Format new text
selectedText = '<em>' + selectedText + '</em>';
// Make changes
// window.setSelection() if only it exists, but I couldn't find alternative?
}
});
<textarea>Lorem ipsum dolor sit amet</textarea>
你可以substring
用来做上面的 .ie :
jQuery('textarea').on('keydown', function(e) {
// If key press combination is CTRL+i
if (e.ctrlKey && e.key == 'i') {
//getting length of text
var length = $('#abc').val().length;
//starting text
var start_point = $('#abc')[0].selectionStart;
//ending text
var end_point = $('#abc')[0].selectionEnd;
//getting selected text
var selectedText = $('#abc').val().substring(start_point, end_point);
console.log(selectedText);
var replacement = "<em>" + selectedText + "</em>";
$('#abc').val($('#abc').val().substring(0, start_point) + replacement + $('#abc').val().substring(end_point, length));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<textarea id="abc">Lorem ipsum dolor sit amet</textarea>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句