可编辑的div
// 加上contenteditable="true"即可,需要注意的是内部添加的子元素默认也可编辑 <div contenteditable="true" class="edit"></div>
<script>
var div = document.querySelector(".edit");
// 创建一个MutationObserver实例
var observer = new MutationObserver(this.divcontentchange);
// 开始监听盒子的变化
observer.observe(div, {
characterData: true, // 监听字符数据变化
childList: true, // 监听子节点变化
subtree: true // 监听子树的变化
});
//盒子内容变化
divcontentchange(mutations) {
mutations.forEach(function (mutation) {
console.log("盒子内容发生了变化!", mutation);
console.log("新的内容是:" + mutation.target.textContent);
});
}
</script>
div设置光标位置
<div contenteditable="true" id="editor"></div> <script> let editor = document.getElementById('editor'); // 将光标设置到开头 editor.focus(); let range = document.createRange(); range.selectNodeContents(editor); range.collapse(true); let sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); // 将光标设置到结尾 editor.focus(); range = document.createRange(); range.selectNodeContents(editor); range.collapse(false); sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); // 将光标设置到指定位置 editor.focus(); range = document.createRange(); range.setStart(editor.childNodes[3], 5); range.collapse(true); sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); </script>
js 创建dom
var myDiv = document.querySelector(".edit"); //创建dom var newspan = document.createElement("span"); //添加标签属性 newspan.setAttribute("contenteditable", false); //添加类名 newspan.className = “classname”; //添加内容 newspan.innerText = treeItem.treealias; //添加节点 myDiv.appendChild(newspan); // 获取myDiv下所有子元素 var childElements = myDiv.children; //获取父元素下最后一个子元素 var lastChildElement = myDiv.lastElementChild; //删除指定子元素 myDiv.removeChild(lastChildElement);
获取盒子样式属性
<input class="input" style="top: 0;left: 7px" v-model="text" autofocus ref="input" type="text" ></input> <script> //这里必须是行内样式才能获取到 //提前写了绝对定位,这里演示改变left值 let input = this.$refs.input; let top = input.style.getPropertyValue("top"); //获取样式属性top let left = input.style.getPropertyValue("left"); //获取样式属性left let left_i = left.indexOf("p"); let left_num = parseInt(left.slice(0, left_i)); //处理成数值 input.style.left = left_num + offset + "px"; </script>
标签:document,dom,js,editor,range,let,关于,sel,left From: https://www.cnblogs.com/guozhongbo/p/17636759.html