编写一个可以创建简易族谱图的网页
时间: 2024-02-11 10:07:12 浏览: 28
好的,这是一个简单的HTML、CSS和JavaScript代码示例,用于创建一个可以创建简易族谱图的网页:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>族谱图</title>
<style>
/* 定义样式 */
#tree {
display: flex;
justify-content: center;
align-items: center;
margin-top: 50px;
}
.node {
width: 100px;
height: 50px;
border: 1px solid black;
text-align: center;
font-size: 16px;
line-height: 50px;
margin: 0 20px;
position: relative;
}
.node:before, .node:after {
content: "";
position: absolute;
left: 50%;
bottom: -25px;
border-top: 1px solid black;
width: 1px;
height: 25px;
}
.node:before {
left: -20px;
}
.node:after {
left: 20px;
}
</style>
</head>
<body>
<div>
<!-- 用户输入表单 -->
<label for="name">姓名:</label>
<input type="text" id="name" placeholder="请输入姓名">
<label for="father">父亲:</label>
<input type="text" id="father" placeholder="请输入父亲姓名">
<label for="mother">母亲:</label>
<input type="text" id="mother" placeholder="请输入母亲姓名">
<button onclick="addNode()">添加</button>
</div>
<div id="tree">
<!-- 初始根节点 -->
<div class="node">根节点</div>
</div>
<script>
// 定义节点数据结构
class Node {
constructor(name, father, mother) {
this.name = name;
this.father = father;
this.mother = mother;
}
}
// 初始根节点
let rootNode = new Node("根节点", null, null);
// 添加节点函数
function addNode() {
let name = document.getElementById("name").value;
let father = document.getElementById("father").value;
let mother = document.getElementById("mother").value;
// 创建新节点
let newNode = new Node(name, father, mother);
// 找到父节点
let parent = findNode(rootNode, father, mother);
// 添加新节点
if (parent) {
let nodeDiv = document.createElement("div");
nodeDiv.className = "node";
nodeDiv.innerHTML = name;
document.getElementById("tree").appendChild(nodeDiv);
connectNodes(parent, nodeDiv);
} else {
alert("找不到父节点!");
}
}
// 查找节点函数
function findNode(node, father, mother) {
if (!node) {
return null;
}
if (node.name === father || node.name === mother) {
return node;
}
let result = findNode(node.father, father, mother);
if (result) {
return result;
}
return findNode(node.mother, father, mother);
}
// 连接节点函数
function connectNodes(parent, child) {
let parentRect = parent.getBoundingClientRect();
let childRect = child.getBoundingClientRect();
let offsetX = parentRect.left - childRect.left;
let offsetY = parentRect.top - childRect.top;
child.style.transform = `translate(${offsetX}px, ${offsetY}px)`;
}
</script>
</body>
</html>
```
这个网页包含一个用户输入表单和一个用于展示族谱图的区域。用户可以在输入表单中输入姓名、父亲姓名和母亲姓名,然后点击“添加”按钮来添加一个新的节点到族谱图中。
当用户点击“添加”按钮时,JavaScript代码会根据用户输入的姓名、父亲姓名和母亲姓名创建一个新节点,然后通过查找父亲节点和母亲节点来确定新节点的父节点,最后将新节点添加到族谱图中,并使用CSS样式来将新节点与父节点连接起来。