复制粘贴按钮实现

//引入jQuery.js

<script>
var select = function(){
return window.getSelection ? window.getSelection().toString() : document.selection.createRange();
};
// 获取光标位置
function getCursortPosition(textDom) {
console.log(textDom);
var cursorPos = 0;
if (document.selection) {
// IE Support
var selectRange = document.selection.createRange();
selectRange.moveStart ('character', -textDom.value.length);
cursorPos = selectRange.text.length;
}else if (textDom.selectionStart || textDom.selectionStart*1 === 0) {
// Firefox support
cursorPos = textDom.selectionStart;
}
return cursorPos;
}
// 设置光标位置
function setCaretPosition(textDom, pos){
if(textDom.setSelectionRange) {
// IE Support
textDom.focus();
textDom.setSelectionRange(pos, pos);
}else if (textDom.createTextRange) {
// Firefox support
var range = textDom.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}


/**
* 添加右键菜单
*/
var $ul = $('<ul class="list-group" id="rightMenu" style="position: absolute; top: 100px; left: 200px;">' +
'<li class="list-group-item" id="copyItem" style="cursor: pointer">复制</li>' +
'<li class="list-group-item" id="pasteItem">黏贴</li>' +
'</ul>');

var copy = '', target;
$('#body').on('contextmenu', function(e) {
//alert('fffffffffffffffff')
var $menu = $('#rightMenu');

// 这一步是为了,每次都把当前的input 换成当前的。
target = e.target;

/**
* 如果 $menu.length > 0
* 则 !!menu.length === true
* 也就是说,右键菜单已经存在,则只需要显示
*/
if(!!$menu.length) {
$menu.show();
} else {
/**
* 如果不存在,则添加右键菜单以及事件
*/
$('body').append($ul);

/**
* 复制
*/
$('#copyItem').on('click', function copyItem() {
// e.stopPropagation();
target.focus()
copy = select();
console.log('复制', copy)

$('#rightMenu').hide()
});

/**
* 黏贴
*/
$('#pasteItem').on('click', function pasteItem() {
var value = $(target).val(), startText = '', endText = '';

// 设置当前目标点 focus 状态
target.focus()

// 检查当前目标点是否有选中的内容
var _copy = select();

/**
* 如果当前文本框中有选中该的内容
* 则替换选中的内容
*/
if(_copy) {
var start = value.indexOf(_copy);
startText = value.substring(0, start);
endText = value.substring(start + _copy.length); // 后面的部分,等于截取 substring(选中前面部分 + 拷贝的部分个数)

/**
* 当前文本的内容等于,选中前面部分 + 拷贝的部分 + 选中后面的部分
*/
target.value = startText + copy + endText;

/**
* 重新设置光标的位置
* 光标位置等于光标的初始位置 + 拷贝的字段的个数
*/
setCaretPosition(target, start + copy.length)
} else {
/**
* 否则将文字插入到光标的位置
*/
var foursIndex = getCursortPosition(target); // 获取光标位置
startText = value.substring(0, foursIndex);
endText = value.substring(foursIndex);

/**
* 当前文本的内容等于,光标前面部分 + 拷贝的部分 + 光标后面的部分
*/
target.value = startText + copy + endText;

/**
* 重新设置光标的位置
* 光标位置等于光标的初始位置 + 拷贝的字段的个数
*/
setCaretPosition(target, foursIndex + copy.length)
}
$('#rightMenu').hide();
});


}


$ul.css('left', e.clientX);
$ul.css('top', e.clientY);

 

return false
});
</script>

 

posted @ 2018-10-19 14:14  笨笨!  阅读(849)  评论(0编辑  收藏  举报