双击时 JavaScript 在文本区域中添加行

标签 javascript jquery

我正在尝试做的事情:

  1. 双击文本区域中的一行。
  2. 防止文本被选择。
  3. 在该行前面添加一个破折号。

我知道一些基本的jquery,但似乎无法理解所需的较低级别的javascript。这是我到目前为止所拥有的:

$("textarea").dblclick(function() {

   //TODO: Prevent selection


   //TODO: Get the line number??


   //TODO: prepend a dash to the line
   // or replace the line with itself
   // plus the dash at the front??


});

Here is the fiddle .

最佳答案

您可能需要做很多事情,但这样的事情应该足以让您开始:

$("textarea").dblclick(function() {
    //first, get the position of the cursor
    var cursorPosition = $(this).prop("selectionStart");

    //get the text value at the cursor position
    var textValue = $(this).val().substr(cursorPosition,1);

    //use a loop to look backward until we find the first newline character \n
    while(textValue != '\n' && cursorPosition >= 0) {
        cursorPosition--;
        textValue = $(this).val().substr(cursorPosition,1);
    }
    //update the textarea, combining everything before the current position, a dash, and everything after the current position.
    $(this).val(($(this).val().substr(0,cursorPosition+1) + '-' + $(this).val().substr(cursorPosition+1)))

});

您可以在这个 JS Fiddle 中看到一个示例:

http://jsfiddle.net/igor_9000/4zk5otvm/2/

您可能需要添加更多内容,具体取决于您希望能够使用该函数执行什么操作以及您想要强制执行哪些限制,但这应该足以让您开始。希望有帮助!

关于双击时 JavaScript 在文本区域中添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35992390/

相关文章:

javascript - functions@lint 脚本失败

javascript - Swiper js 附加和前置不适用于多个实例

javascript - Object.defineProperty 如何为对象中的所有未知子对象设置 getter 和 setter

jquery - 将 jQuery Datepicker 添加到动态添加的 <input>

jquery - 使用 Bootstrap 更改背景和 CSS

javascript - 在多个固定高度的表格中自动滚动

javascript - 我可以在(加载的)页面上运行我自己的 javascript 吗?

javascript - 删除表中的最后一行

javascript - 使用 JQuery,如何引用同级的第一个选项?

javascript - 隐藏元素后使用 jQuery 在 Firefox 中平滑调整页面大小