【发布时间】:2017-05-08 16:35:07
【问题描述】:
我是 jquery 的初学者,但在可拖动小部件方面遇到了一些问题。 单击“按钮”时,选择器似乎无法获取下一个可拖动类。 问题是我不能为选择器使用 ID,因为表格是动态填充的,并且行数会有所不同。 有没有办法只改变javascript来解决这个问题? 谢谢大家的努力!
这里的代码笔:https://codepen.io/Zerberuus/pen/aWENje
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<table> <THEAD>
<TR>
<TH>col1</TH>
<TH>col2</TH>
<TH>col3</TH>
<TH>col4</TH>
<TH>col5</TH>
</TR></THEAD>
<TBODY><TBODY><TR>
<TD>random</TD>
<TD>random2</TD>
<TD class="press" style="color:blue;">clickhere</TD>
<div class="draggable">
<p>Drag me around</p>
<p>Box 1</p>
</div>
<TD class="press" style="color:red;">clickhere2</TD>
<div class="draggable">
<p>Drag me around</p>
<p>Box 2</p>
</div>
<TD>random3</TD>
</TR></TBODY></table>
</body>
</html>
JS:
$(document).ready(function(){
$( ".draggable" ).draggable(); //init draggable
$(".draggable").hide(); //hide at first
$(".press").click(function () { // fadeIn the next .draggable class
$(this).next(".draggable:first").fadeIn("slow");
});
}); //end of script
CSS:
.draggable{
position:relative;
width: auto;
height: auto;
padding: 0.5em;
line-height: 0px;
border-radius:25px;
border:1px solid #000000;;
display: inline-block;
background-color: #c1c1c1;
}
【问题讨论】:
-
@Nemus 请不要添加 sn-p 只是为了“格式化”HTML。如果您还没有包含正确运行所需的 JavaScript 和 CSS,则 sn-p 是无用的。代码片段旨在以可运行、自包含的方式来演示代码行为。
-
有人可以帮我解决我的问题或有替代可拖动的方法吗?
-
您在
tds 之间混合了div标签。由于这是非法的(div不能是tr的子代),因此divs 被移出table。没有.next('.draggable'),因为所有的可拖动对象都移走了。你可以把.draggable对象变成tds,但是你需要处理定位问题。 -
感谢您的回答。事实上,它适用于 td 等表格元素,但正如你所猜测的那样,我现在遇到了定位问题。有没有办法让未隐藏的元素独立于周围的 td`s?
-
如果您真的不能在指向要拖动元素的
id的按钮上留下data-...属性,我会考虑position: absolute。如果您可以这样做,那么您可以将divs 移到它们所属的table之外,并通过jQuery 的.data()找到它们
标签: javascript jquery jquery-ui jquery-ui-draggable