zoukankan      html  css  js  c++  java
  • 一个简单易懂的javascrip selection&range小案例

    在制作富文本编辑器,尤其是在制作以div元素为编辑器区域时,当鼠标离开编辑区域以后会失去焦点,失去选区,这时候就要通过selection&range来重新设置选区。【以下代码尚未考虑IE低版本,请在现代浏览器下测试学习】

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>range</title>
    	<style type="text/css">
    	#edit{
    		 100%;
    		height: 300px;
    		border: 1px solid #ccc;
    	}
    	</style>
    </head>
    <body>
    	<div contenteditable="true" id="edit">
    		<p>通过一个富文本编辑器,学习JavaScript!</p>
    	</div>
    	<div id="button">button</div>
    	<script type="text/javascript">
    
    	var edit = document.getElementById('edit');
    	var button = document.getElementById('button');
    	
    	edit.addEventListener('mouseup', function() {
    		saveSelection();
    	});
    
    	button.addEventListener('click', function() {
    		restoreSelection();
    		document.execCommand('underline', false, null);
    		saveSelection();
    	});
    
    	function saveSelection() {
    		selection = document.getSelection();
    		save = selection.getRangeAt(0);
    		
    	}
    
    	function restoreSelection() {
    		var selection = window.getSelection();
    
    		if(selection.rangeCount > 0) {
    			selection.removeAllRanges();
    		}
    
    		var range = document.createRange();
    		selection.addRange(save);
    	}
    	
    	</script>
    </body>
    </html>
    

      

  • 相关阅读:
    React中的PropTypes详解
    mobile 更改hosts
    sed用例
    Centos 7 开启端口
    node-gyp rebuild 卡住?
    录制客户端脚本
    创建删除表空间以及表空间使用情况查询
    oracle 修改字符集 修改为ZHS16GBK
    linux中压缩、解压缩命令详解
    jps、jstack、jmap、jhat、jstat、hprof使用详解
  • 原文地址:https://www.cnblogs.com/chenshuo/p/4580457.html
Copyright © 2011-2022 走看看