我昨天做了一些非常相似的事情,所以为什么不分享:)
我的目标是将文本元素放到我的 textarea 上,在两行文本的中间,同时显示一个指示符指向它的放置位置。相信对你有用!;)
$(document).ready(function() {
var lineHeight = parseInt($('#textarea').css('line-height').replace('px',''));
var previousLineNo = 0;
var content = $('#textarea').val();
var linesArray = content.length > 0 ? content.split('\n') : [];
var lineNo = 0;
var emptyLineAdded = false;
$('.draggable').draggable({
revert: function(is_valid_drop) {
if (!is_valid_drop) {
$('#textarea').val(content);
return true;
}
},
drag: function(event, ui) {
lineNo = getLineNo(ui, lineHeight);
if (linesArray.length > 0 && previousLineNo != lineNo) {
insertWhiteLine(lineNo, linesArray);
}
previousLineNo = lineNo;
}
});
$("#textarea").droppable({
accept: ".draggable",
drop: function( event, ui ) {
appendAtLine(lineNo, linesArray, ui.draggable.text());
$(ui.draggable).remove();
content = $('#textarea').val();
linesArray = content.split('\n');
if (linesArray[linesArray.length - 1] == '')
linesArray.pop(); //remove empty line
}
});
$('#textarea').on('input', function() {
if (!emptyLineAdded) {
console.log('input !');
console.log($('#textarea').val());
content = $('#textarea').val();
linesArray = content.split('\n');
if (linesArray[linesArray.length - 1] == '')
linesArray.pop(); //remove empty line
}
});
});
//Returns the top position of a draggable element,
//relative to the textarea. (0 means at the very top of the textarea)
function getYPosition(element, lineHeight) {
var participantIndex = $(element.helper.context).index();
var initPos = participantIndex * lineHeight;
var actualPos = initPos + element.position.top;
return actualPos;
}
//Returns the line number corresponding to where the element
//would be dropped
function getLineNo(element, lineHeight) {
return Math.round(getYPosition(element, lineHeight) / lineHeight);
}
//Inserts a white line at the given line number,
//to show where the element would be dropped in the textarea
function insertWhiteLine(lineNo, linesArray) {
$('#textarea').val('');
$(linesArray).each(function(index, value) {
if (index < lineNo)
$('#textarea').val($('#textarea').val() + value + '\n');
});
emptyLineAdded = true;
$('#textarea').val($('#textarea').val() + '_____________\n'); //white line
emptyLineAdded = false;
$(linesArray).each(function(index, value) {
if (index >= lineNo)
$('#textarea').val($('#textarea').val() + value + '\n');
});
}
//Inserts content of draggable at the given line number
function appendAtLine(lineNo, linesArray, content) {
$('#textarea').val('');
$(linesArray).each(function(index, value) {
if (index < lineNo)
$('#textarea').val($('#textarea').val() + value + '\n');
});
$('#textarea').val($('#textarea').val() + content + '\n'); //content to be added
$(linesArray).each(function(index, value) {
if (index >= lineNo)
$('#textarea').val($('#textarea').val() + value + '\n');
});
}