i want to make a draggable div with jquery just only move in its parentdrag only in horizontal not vertical
To create a draggable div with jQuery that only moves in its parent and only in the horizontal direction, you can use the jQuery UI library and the draggable() method. Here is an example code snippet:
HTML:
<div class="parent">
<div class="draggable"></div>
</div>
CSS:
.parent {
width: 500px;
height: 300px;
border: 1px solid black;
position: relative;
}
.draggable {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
cursor: move;
}
JavaScript:
$(document).ready(function() {
$(".draggable").draggable({
axis: "x",
containment: "parent"
});
});
Explanation:
- We create a parent div with a fixed width and height and a red draggable div inside it.
- We set the position of the parent div to relative and the position of the draggable div to absolute, so that it can move freely within the parent div.
- We use the transform property to center the draggable div horizontally and vertically.
- We set the cursor property to "move" to indicate that the draggable div can be moved.
- We use the jQuery UI library and the draggable() method to make the draggable div draggable.
- We set the axis option to "x" to restrict the movement to the horizontal direction.
- We set the containment option to "parent" to restrict the movement to the parent div.
原文地址: https://www.cveoy.top/t/topic/bLDK 著作权归作者所有。请勿转载和采集!