【问题标题】:newly created dom elements cannot be draggable新创建的 dom 元素不能拖动
【发布时间】:2015-08-01 20:05:23
【问题描述】:

我正在使用 jquery 和 jquery ui 创建可拖动元素。 我在https://jsfiddle.net/2j2c8vLc/ 创建了一个小的 jsfiddle 示例 这证明了我正在尝试做的事情。

javascript代码:

$(function(){
    $('body').append('<div id="moshe">hi</div>');
    $('#moshe').draggable();
});

在示例中,我在文档就绪事件之后向正文添加了一个 div 元素,然后尝试使其可拖动。结果是它不可拖动,类被添加到元素中但似乎还不够。

有什么想法吗?

更新

更多信息以清除问题..我正在尝试移动只读文本输入。

我在 http://jsfiddle.net/70f3dbLh/2/ 创建了新的 jsfiddle 使用以下 javascript 代码:

$(document).ready(function(){
    $("<div>").attr("id", "moshe").html("<input readonly type=\"text\"></input>").appendTo("body").draggable();
});

如您在此处所见.. div 内的文本输入不可拖动

我尝试创建另一个示例,尝试创建没有 div 的文本输入并使其可拖动......结果相同。它不可拖动。

jsfiddle http://jsfiddle.net/70f3dbLh/3/

javascript代码:

$(document).ready(function(){
    $("<input readonly value=\"aaa\" type=\"text\"></input>").attr("id", "moshe").appendTo("body").draggable();
});

【问题讨论】:

  • 您的代码运行良好。这是您发布的链接中特定小提琴的问题。试试这个小提琴 (jsfiddle.net/5swu6358),它包含你的代码,并且可以工作。

标签: javascript jquery jquery-ui


【解决方案1】:

使用以下 jsfiddle:http://jsfiddle.net/70f3dbLh/1/ 并查看:http://jsfiddle.net/70f3dbLh/1/show/

代码类似于

$(document).ready(function(){
    $("<div>").attr("id", "moshe").html("hi").appendTo("body").draggable();
});

然后就可以拖动了。

更新您的更新 我更新了我的帖子,因为你更新了你的帖子。

我添加了一个新的 jsfiddle。 http://jsfiddle.net/8scyhq01/2/ 一般情况下,输入框是不可拖动的,但是如果你在输入框上面放了一层,那么这个层就可以拖动了。并且输入字段也会被拖动。

$("<div>").addClass("layer").attr("id", "moshe").html("<div class=\"layer\"></div><input readonly type=\"text\"></input>").appendTo("body").draggable();

【讨论】:

  • 感谢您的回答,尝试拖动不起作用的文本输入。更新了我的主要帖子。
【解决方案2】:

我已经修改 我找到的代码From this post 使文本输入可拖动,并在其顶部放置一个 div。

 $(function() {
     $( "#resizable" ).resizable({
containment: "#container"
});
     $( "#draggable" ).draggable({containment: "#container"});
});
 #container { width: 300px; height: 300px; }
#container h3 { text-align: center; margin: 0; margin-bottom: 10px; }
#resizable, #container { padding: 0.5em; }
#d{ 
  background:blue;
  width:100px; 
  height:30px;
  position:relative;
  top: 2em;
  left:0em;
  z-index:9;
  opacity:0.1;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>


<div id="container" class="ui-widget-content">
<h3 class="ui-widget-header">Containment</h3>
    <span id="draggable"><div id='d'></div>
<input type="text "id="resizable" class="ui-state-active" readonly value="This is input box">
</span>
</div>

【讨论】:

    猜你喜欢
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2018-09-06
    相关资源
    最近更新 更多