拖动
效果如图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
margin: 30px;
}
.box {
width: 300px;
height: 300px;
border: 1px solid #000;
display: inline-block;
position: relative;
/* box-sizing: border-box; */
overflow: auto;
font-size: 0;
}
img {
/* float: left; */
width: 100px;
height: 100px;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="main">
<div class="box box1">
<img src="./img/1.png" id="img1" alt="">
<img src="./img/2.png" id="img2" alt="">
<img src="./img/3.png" id="img3" alt="">
<img src="./img/4.png" id="img4" alt="">
<img src="./img/5.png" id="img5" alt="">
<img src="./img/6.png" id="img6" alt="">
<img src="./img/7.png" id="img7" alt="">
</div>
<div class="box box2"></div>
<div class="box box3"></div>
</div>
<script>
/*
利用事件委托处理多个可拖动的元素
*/
function $(name) {
return document.querySelector(name)
}
let mainBox = $(".main")
// 1.将元素设置成可拖放的
mainBox.ondragstart = function (e) {
// 获取拖动元素的信息 利用setData方法
e.dataTransfer.setData("Text", e.target.id)
}
mainBox.ondragover = function (e) {
e.preventDefault()
}
// 想要触发ondrop事件,需要在ondragover里面阻止默认行为
mainBox.ondrop = function (e) {
let elem = e.dataTransfer.getData('Text')
e.target.appendChild(document.getElementById(elem))
}
</script>
</body>
</html>
问题1:
image图片之间的间隙消除