网页复制文字

复制固定文字(点击复制复制指定文字)

<div class="u_div">
     <div id="wxnum">123456</div>
     <a href="javascript:void(0);" id="copyBtn">复制</a>
 </div>
 <script type="text/javascript">
	function copyArticle(event) {
	    const range = document.createRange();
	    range.selectNode(document.getElementById('wxnum'));
	    const selection = window.getSelection();
	    if(selection.rangeCount > 0) selection.removeAllRanges();
	    selection.addRange(range);
	    document.execCommand('copy');
	    alert("复制成功!");
	  }
	document.getElementById('copyBtn').addEventListener('click', copyArticle, false);
</script>

鼠标选取文字(移动端不适应)

$(document).ready(function () {
	$(".contenttext").mouseup(function (e) {
		var txt;
		var parentOffset = $(this).offset();
		var x = e.pageX - parentOffset.left;
		var y = e.pageY - parentOffset.top;
		txt = window.getSelection();
		if (txt.toString().length > 1) {
			alert(txt);
		}
	});
});

选取文字(window.getSelection()网页中选取的地方)

$('button').click(function(){
	console.log(window.getSelection().toString())
})

猜你喜欢

转载自blog.csdn.net/oyy_1126/article/details/101444861