以下是一个简单的树型穿梭框的示例代码(使用HTML、CSS和JavaScript):
HTML部分:
<div id="tree"><ul><li><span>节点1</span><ul><li><span>节点1.1</span></li><li><span>节点1.2</span></li></ul></li><li><span>节点2</span><ul><li><span>节点2.1</span></li><li><span>节点2.2</span></li></ul></li></ul>
</div><div id="shuttle"><select multiple></select><button id="toRight">→</button><button id="toLeft">←</button>
</div>
CSS部分:
#tree ul {list-style-type: none;padding-left: 20px;
}#tree span {cursor: pointer;
}#shuttle {margin-top: 20px;
}#shuttle button {margin-top: 5px;margin-bottom: 5px;
}
JavaScript部分:
// 获取树型结构中所有的树节点
const treeNodes = document.querySelectorAll("#tree span");// 获取穿梭框的相关元素
const selectBox = document.querySelector("#shuttle select");
const toRightBtn = document.querySelector("#toRight");
const toLeftBtn = document.querySelector("#toLeft");// 点击树节点时触发的事件处理程序
function treeNodeClick(event) {const nodeText = event.target.textContent;// 判断是否已经存在于穿梭框中,若不存在则添加到穿梭框中if (!selectBox.querySelector(`option[value="${nodeText}"]`)) {const option = document.createElement("option");option.value = nodeText;option.textContent = nodeText;selectBox.appendChild(option);}
}// 点击右移按钮时触发的事件处理程序
function moveToRight() {const selectedOptions = selectBox.selectedOptions;// 移动所有被选中的选项到右侧Array.from(selectedOptions).forEach(option => {option.remove();document.querySelector(`#tree span:contains(${option.value})`).classList.remove("selected");});
}// 点击左移按钮时触发的事件处理程序
function moveToLeft() {const selectedOptions = selectBox.selectedOptions;// 移动所有被选中的选项到左侧Array.from(selectedOptions).forEach(option => {const span = document.querySelector(`#tree span:contains(${option.value})`);if (span) {span.classList.add("selected");} else {const li = document.createElement("li");const newSpan = document.createElement("span");newSpan.textContent = option.value;newSpan.classList.add("selected");li.appendChild(newSpan);document.querySelector("#tree ul").appendChild(li);}option.remove();});
}// 为树节点添加点击事件监听器
treeNodes.forEach(node => {node.addEventListener("click", treeNodeClick);
});// 为右移按钮添加点击事件监听器
toRightBtn.addEventListener("click", moveToRight);// 为左移按钮添加点击事件监听器
toLeftBtn.addEventListener("click", moveToLeft);
请将以上代码复制到一个HTML文件中并在浏览器中打开以查看效果。在树型结构中点击节点,然后点击右移按钮可将节点移动到穿梭框中,点击左移按钮可将选定的节点移回到树型结构中。