xg-project-library/html/1.html

88 lines
2.8 KiB
HTML
Raw Normal View History

2024-11-15 03:24:03 +00:00
<!DOCTYPE html>
<html lang="en">
2024-11-15 10:59:31 +00:00
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
html,body{
height: 100%;
}
body {
background-color: lightblue;
display: flex;
justify-content: center;
align-items: center;
}
.container {
width: 200px;
height: 200px;
border: 8px solid;
margin-left: 20px;
}
.content {
width: 184px;/* width: 100px; */
height: 184px;/* height: 100px; */
background: url(./flower.jpg) center/cover;
}
.hide {
display: none;
}
.active {
border: 8px dashed #ccc;
background-color: lightgoldenrodyellow;
}
</style>
</head>
<body>
<div class="container">
<div class="content" draggable="true"></div>
</div>
<div class="container"></div>
<div class="container"></div>
<div class="container"></div>
<div class="container"></div>
<script>
//拖拽的元素
const content = document.querySelector('.content')
content.addEventListener('dragstart', dragstart)
function dragstart(){
setTimeout(() =>{ //setTimeout可以让元素不要消失得这么快
this.classList.add('hide') //当拖拽开始时隐藏该元素
})
}
content.addEventListener('dragend',dragend)
function dragend(){
this.classList.remove('hide') //当拖拽结束时显示该元素
}
//目标元素
const container = document.querySelectorAll('.container')
container.forEach((item)=>{
item.addEventListener('dragleave',dragleave)
item.addEventListener('dragenter',dragenter)
item.addEventListener('dragover',dragover)
item.addEventListener('drop',drop)
})
function dragleave() {
this.classList.remove('active') //当元素移出该区域时,取消高亮
}
function dragenter() {
this.classList.add('active') //当元素移动到该区域上时高亮显示
}
//drop事件要和dragover事件一起使用才有效果注意阻止事件
function dragover(e){
e.preventDefault();
}
function drop(e){ //当拖拽元素在目标元素上同时鼠标放开时,需要将拖拽元素放到这个容器中
e.preventDefault();
this.append(content) //将拖拽元素放到这个容器中
}
</script>
</body>
</html>