点击复制DIV内内容

JS

//复制文本
function copy(text) {
	selectText(text);
	document.execCommand('copy');
	layer.msg('复制成功');
}
//选中文本
function selectText(element) {
	var text = document.getElementById(element);
	//做下兼容
	if (document.body.createTextRange) {  //如果支持
		var range = document.body.createTextRange(); //获取range
		range.moveToElementText(text); //光标移上去
		range.select();  //选择
	} else if (window.getSelection) {
		var selection = window.getSelection(); //获取selection
		var range = document.createRange(); //创建range
		range.selectNodeContents(text);  //选择节点内容
		selection.removeAllRanges(); //移除所有range
		selection.addRange(range);  //添加range
		/*if(selection.setBaseAndExtent){
		 selection.setBaseAndExtent(text, 0, text, 1);
		 }*/
	} else {
		layer.msg("复制失败");
	}
}

HTML

<b id="text_1">1234</b><span onclick="copy('text_1')">复制</span>
<b id="text_2">4567</b><span onclick="copy('text_2')">复制</span>
相关推荐