Insert text at caret - 插入新行和制表符空格

Insert text at caret - insert new lines and tab spaces

我有一些我之前制作的代码如下所示:

selected = '';

$('img').click(function(){
  console.log($(this).attr('alt'));
 selected = $(this).attr('alt');
});

$('#comments').click(function(){
 insertAtCaret('comments',selected)
  // Clear the selection so it isn't copied repeatedly
  selected = '';
});

function insertAtCaret(areaId,text) {
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
        "ff" : (document.selection ? "ie" : false ) );
    if (br == "ie") { 
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        strPos = range.text.length;
    }
    else if (br == "ff") strPos = txtarea.selectionStart;

    var front = (txtarea.value).substring(0,strPos);  
    var back = (txtarea.value).substring(strPos,txtarea.value.length); 
    txtarea.value=front+text+back;
    strPos = strPos + text.length;
    if (br == "ie") { 
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        range.moveStart ('character', strPos);
        range.moveEnd ('character', 0);
        range.select();
    }
    else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#!"><img src="smiley1.png" alt="{smiley001}"><img src="smiley2.png" alt="{smiley002}"><img src="smiley3.png" alt="{smiley003}"><img src="smiley4.png" alt="{smiley004}"><img src="smiley5.png" alt="{smiley005}"></a><br>
<textarea id="comments" cols="50" rows="10"></textarea>

在此代码中,您单击图片,然后单击文本区域中的 space,图片的 alt 属性将粘贴到插入符号的位置。

我想为一些图片插入制表符 space 和换行,那么我应该为相应图片的 alt 属性设置什么值?

如果我没理解错的话,您是在尝试向 alt 属性添加一些基于空格的文本格式。我认为这是不可能的,它将被浏览器转换为空格。您可以添加一个 data- attribute 来处理这个问题。