jquery ui droppable在鼠标指针的textarea中插入文本

Bub*_*kin 5 jquery jquery-ui

我正在尝试使用jquery ui draggable/droppable拖放到textarea中.我将textarea设置为droppable.我可以在丢弃发生时触发事件,但我无法弄清楚如何准确确定textarea中"drop"发生在哪个位置.

基本上我想在文本区域的精确位置插入文本.

谷歌现在没有帮助我,这让我感到难过.

例:

<html><head><title>Drag Drop Test</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>

<script>
  $(document).ready(function(){

    $( "#catalog li" ).draggable({
      appendTo: "body",
      helper: "clone"
    });

    $( "#mytext" ).droppable({
      accept: ":not(.ui-sortable-helper)",
      drop: function( event, ui ) {
        console.log(ui.position);
        // figure out where in the textarea this is
        // drop in some string
      }
    });
  });
  </script>
</head>
</body>

<div id="products">
  <div id="catalog">
    <h3><a href="#">T-Shirts</a></h3>
    <div>
      <ul>
        <li>Lolcat Shirt</li>
        <li>Cheezeburger Shirt</li>
        <li>Buckit Shirt</li>
      </ul>
    </div>
  </div>
</div>

<textarea id="mytext" cols="60" rows="20">Just some random text.</textarea>

</body></html>
Run Code Online (Sandbox Code Playgroud)

因此,在上面的例子中,我如何找出textarea中哪个位置发生了某个目录li元素的'drop',然后如何将字符串放入textarea中的那个确切位置?

这意味着,如果我将"Lolcat Shirt"拖入#mytext textarea并将其放在"random"和"text"之间,我希望将#mytext textarea值更改为"Just a random Lolcat Shirt text".

这可能吗?非常感谢您的帮助.提前致谢!

Dr.*_*lle 5

除了IE之外,这在浏览器中并不容易,因为你必须使用范围,而其他浏览器没有任何方法可以处理范围内的坐标(你需要什么,将文本放在那里).

但不知何故,你试图重新发明轮子.大多数浏览器(可能全部)允许将所选文本移动到文本区域,因此您需要做的是:onmousedown选择文本 <li>(而不是使其可拖动)