简易编辑器实现原理篇 selection, range, MutationObserver

HTML





    

这是要被插入的结点

JS

	//创建监听者,构造函数接收监听者回调,此处主要监听删除编辑器内节点事件
	const observer = new MutationObserver(function(mutations) {
	    mutations.forEach(function(mutation) {
			mutation.removedNodes.forEach(item => {
				if(item.id === "insertNode") {
					document.querySelector("#box").appendChild(item)
				}
			}) 
	    });
	});
	//配置
	const config = { attributes: true, childList: true, characterData: true };
	//对DOM添加监听
	observer.observe(document.getElementById("editBox"), config);
	//插入函数,
	const insertNode = () => {
		const selection = window.getSelection()
		const range = selection.getRangeAt(0)
		if(range.commonAncestorContainer.id === "editBox" || range.commonAncestorContainer.parentElement.id === "editBox"){
			const box = document.querySelector("#insertNode")
			range.insertNode(box)
		}
	}
	const btnCli = () =>{
		alert("haha")
	}

你可能感兴趣的:(javascript,html,css)