js实现选择文本后弹复制气泡

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Context Menu Example</title>
<style>
    #contextMenu {
        display: none;
        position: absolute;
        background-color: #ddd;
        border-radius: 5px;
        padding: 10px;
        z-index: 1000;
    }
</style>
</head>
<body>
 <br><br><br><br><br>
<div id="content">
    选择这段文本后看看发生了什么。
</div>
 
<div id="contextMenu">
    <p>共选中了 <span id="contextMenuCount"></span> 个字符</p>
    <button onclick="handleContextMenuAction()">复制</button>
</div>
 
<script>
var selection =''
var menu = document.getElementById('contextMenu');
 
 
function hideContextMenu() {
	if(!selection || selection.toString().length===0){
		var menu = document.getElementById('contextMenu');
		menu.style.display = 'none';
	}
}
 
// 处理菜单选项的点击事件
function handleContextMenuAction() {
    //隐藏
	menu.style.display = 'none';
	Toast('复制成功',3);
    //复制 
	let result = false;
	let save = function(e){
		e.clipboardData.setData('text/plain', selection.toString());
		e.preventDefault();
	}
	document.addEventListener('copy', save);
	result = document.execCommand('copy');
	document.removeEventListener('copy',save);
	return result; 
}
 
// 监听mouseup事件来显示菜单
document.getElementById('content').addEventListener('mouseup', function(e) {
     selection = window.getSelection(); // 获取选中内容
	
    if (selection && selection.toString().length > 0) { // 如果有选中内容
        var menu = document.getElementById('contextMenu');
        var count = document.getElementById('contextMenuCount');
        count.textContent = selection.toString().length; // 更新菜单中的字符数
        
        // 计算并设置菜单的位置
        menu.style.left = e.clientX + 'px';
        menu.style.top = e.clientY + 'px';
        
        menu.style.display = 'block';// 显示菜单
    } else {
        hideContextMenu(); // 如果没有选中内容,隐藏菜单
    }
});
 
// 监听文档点击来隐藏菜单
document.addEventListener('click', hideContextMenu);

//提示
function Toast(msg,duration){
      duration=isNaN(duration)?4000:duration;
      var m = document.createElement('div');
      m.innerHTML = msg;
      m.style.cssText="max-width:60%;min-width: 150px;padding:0 5px;height: 40px;color: rgb(255, 255, 255);line-height: 40px;text-align: center;border-radius: 4px;position: fixed;top: 20%;left: 50%;transform: translate(-50%, -50%);z-index: 999999;background:#67C23A;font-size: 16px;";
      document.body.appendChild(m);
      setTimeout(function() {
        var d = 0.5;
        m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
        m.style.opacity = '0';
        setTimeout(function() { document.body.removeChild(m) }, d * 1000);
      }, duration);
}
</script>
 
</body>
</html>

posted on 2024-12-25 09:34  anjun_xf  阅读(26)  评论(0)    收藏  举报

导航

TOP