效果:
h布局生成左右布局,
v布局生成上下布局
代码:文章来源:https://www.toymoban.com/news/detail-785270.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./jquery.min.js"></script>
<link rel="stylesheet" href="./index.css">
<title>Document</title>
</head>
<body>
<div class="box">
<div class="left">
<div class="btn btn1" draggable="true">H布局</div>
<div class="btn btn2" draggable="true">V布局</div>
</div>
<div class="right " ondrop="handleDrop(event)" ondragover="allowDrop(event)">
</div>
</div>
<script>
let btn1 = document.querySelector('.btn1')
let btn2 = document.querySelector('.btn2')
let right = document.querySelector('.right')
btn1.addEventListener('dragstart',function(e) {
e.dataTransfer.setData("text/plain", "1");
})
btn1.addEventListener('dragover',function(event){
event.preventDefault()
})
btn2.addEventListener('dragstart',function(e) {
console.log(e,'111')
e.dataTransfer.setData("text/plain", "2");
})
btn2.addEventListener('dragover',function(event){
event.preventDefault()
})
function allowDrop(e) {
e.preventDefault();
}
function handleDrop(e) {
e.preventDefault();
var data = e.dataTransfer.getData("text/plain");
if(data==1) {
e.target.innerHTML = `
<div class="row">
<div class="row-item"></div>
<div class="row-item"></div>
</div>
`
}else {
e.target.innerHTML = `<div class="col">
<div class="col-item"></div>
<div class="col-item"></div>
</div>`
}
}
</script>
</body>
</html>
css 文件:文章来源地址https://www.toymoban.com/news/detail-785270.html
.box {
margin: 10px;
display: flex;
.left {
width: 200px;
.btn {
width: 100px;
height: 40px;
line-height: 40px;
background-color: cyan;
color: #fff;
text-align: center;
margin-bottom: 20px;
}
}
.right {
flex:1;
border: 1px solid #000;
min-height: 400px;
}
}
div {
box-sizing: border-box;
}
.df {
flex:1;
}
.row {
display: flex;
width: 100%;
height: 100%;
.row-item {
flex: 0 0 50%;
// border: 1px solid #dedede;
height: 100%;
&:first-child {
position: relative;
&::after {
content: '';
position: absolute;
width: 1px;
height: 100%;
background: #000;
top: 0;
right: 0;
}
}
}
}
.col {
display: flex;
width: 100%;
height: 100%;
flex-direction: column;
.col-item {
// border: 1px solid #dedede;
flex: 0 0 50%;
// border-bottom: 1px solid #dedede;
// border-right: 1px solid #dedede;
height: 100%;
&:first-child {
position: relative;
&::after {
content: '';
position: absolute;
height: 1px;
width: 100%;
background: #000;
left: 0;
bottom: 0;
}
}
}
}
到了这里,关于js 实现拖动按钮添加布局的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!