我正在尝试使用jQuery UI Draggable和Droppable组件在<div>
内拖放<input>
元素。目前,我必须将插入符号放在我希望文本显示的位置,然后将<div>
拖放到<input>
。
我不是100%确定是否可以这样做,但我想要做的是让我们在<div>
的文本之间拖动<input>
时自动更新其位置。
.draggable
{
width: 250px;
height: 20px;
background-color: #e6eaff;
border: 2px solid #3399cc;
margin-bottom: 1em;
padding: 4px;
cursor: default;
}
.active
{
border: 2px solid #6699ff;
}
#droppable
{
font-size: 14pt;
width: 400px;
}
#droppableHolder
{
margin-top: 5em;
}
<div class="draggable">Text 1</div>
<div class="draggable">Text 2</div>
<div class="draggable">Text 3</div>
<div class="draggable">Text 4</div>
<div id="droppableHolder">
Drop in the text box below:<br />
<br />
<input type="text" id="droppable" value="INSERT ANYWHERE" />
</div>
$(".draggable").draggable({
revert: true,
//revert: false,
helper: 'clone',
start: function(event, ui) {
$(this).fadeTo('fast', 0.5);
//$(this).css('cursor', 'text');
//$(this).hide();
},
stop: function(event, ui) {
$(this).fadeTo(0, 1);
//$(this).show("explode", { pieces: 16 }, 2000);
}
});
$("#droppable").droppable({
hoverClass: 'active',
drop: function(event, ui) {
//this.value += $(ui.draggable).text();
//alert($("#droppable"));
insertAtCaret("droppable", $(ui.draggable).text());
},
over: function(event, ui) {
//$(this).css('cursor', 'text');
}
});
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;
}