<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h2>Kéo thả vị trí các thẻ và chỉnh sửa nội dung với jQuery UI</h2>
<p>Để chỉnh sửa nội dung, nhấp đôi chuột vào thẻ cần chỉnh sửa</p>
<div id="layout">
<div id="about">Nội dung About</div>
<div id="count">Nội dung Count</div>
</div>
<div id="position">
Vị trí: <span>about,count</span>
</div>
<script src="script.js"></script>
</body>
</html>
#layout {
border: 2px solid #ccc;
padding: 10px;
min-height: 150px;
margin-bottom: 20px;
display: flex;
flex-direction: column;
gap: 10px;
background-color: #f9f9f9;
}
#layout div {
border: 1px solid #aaa;
padding: 20px;
background-color: #fff;
cursor: move;
transition: background-color 0.3s;
}
#layout div:hover {
background-color: #e9e9e9;
}
#about {
background-color: #a4c4ff;
}
#count {
background-color: #ffa4a4;
}
#position {
border: 1px solid #5cb85c;
padding: 10px;
background-color: #dff0d8;
font-family: monospace;
font-size: 1.2em;
}
// Đợi cho tài liệu HTML được tải xong
$(document).ready(function() {
// Kích hoạt chức năng kéo thả và sắp xếp cho các thẻ con của #layout
$("#layout").sortable({
// Khi một phần tử được sắp xếp xong
update: function(event, ui) {
// Lấy danh sách các id của các phần tử con theo thứ tự mới
const sortedIDs = $(this).sortable('toArray', { attribute: 'id' });
// Chuyển mảng thành chuỗi để hiển thị
const positionText = sortedIDs.join(',');
// Cập nhật nội dung của thẻ #position
$("#position span").text(positionText);
}
});
// Vô hiệu hóa việc chọn văn bản khi kéo
$("#layout").disableSelection();
// Thêm chức năng chỉnh sửa nội dung
$("#layout div").on("dblclick", function() {
const currentText = $(this).text();
const $this = $(this); // Lưu lại đối tượng JQuery hiện tại
// Tạo một thẻ input với nội dung hiện tại
const $input = $("<input type='text' />").val(currentText);
// Thay thế nội dung div bằng input
$this.html($input);
// Tự động focus vào input để người dùng có thể gõ ngay
$input.focus();
// Xử lý khi người dùng nhấn Enter hoặc click ra ngoài
$input.on("keypress", function(e) {
if (e.which === 13) { // Mã phím Enter
const newText = $(this).val();
$this.text(newText);
}
}).on("blur", function() { // Sự kiện khi click ra ngoài
const newText = $(this).val();
$this.text(newText);
});
});
});