我之前有一些代码,如下所示:
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>
在此代码中,您单击图片然后单击textarea中的空格,图片的alt属性将粘贴在插入符号的位置。
我想为某些图片插入标签空格和新行,那么我会为相应图像的alt属性添加哪些值?
答案 0 :(得分:0)
如果我理解正确,您正在尝试向alt属性添加一些基于空格的文本格式。我不认为这是可能的,它将被浏览器转换为空格。您可以添加data- attribute来处理此问题。