通过浏览器本机上下文菜单粘贴自定义div

时间:2013-04-24 14:09:58

标签: javascript contextmenu copy-paste

我有一个<div>块,我希望用户能够通过浏览器本机上下文菜单粘贴数据。 contenteditable="true"不是可接受的解决方案。 Ace editorhttp://ace.ajax.org/build/kitchen-sink.html)将<textarea>放在mousedown事件的鼠标光标下。我试过这样的事情:

<div class="container">
 <div id="editor"></div>
 <textarea id="paste-container"></textarea>
</div>
#container {
 position: relative;
}

#editor {
 width: 100px;
 height: 100px;
}

#paste-container {
 position: absolute;
 width: 100px;
 height: 100px;
 display: none;
 opacity: 0;
}
var editor = document.querySelector('#editor'),
    paste = document.querySelector('#paste-container');

editor.onmousedown = function () {
 paste.style.display = "block";
 setTimeout(function () {
  paste.style.display = "none";
 }, 0);
}

但我没有得到textarea的菜单。请告诉我,如何以这种方式获取用户的粘贴数据?

1 个答案:

答案 0 :(得分:0)

所以我找到了解决方案。您需要在<textarea>事件上为contextmenu设置选择。像这样的东西:

editor.onmousedown = function () {
 paste.style.display= 'block';
};

editor.onmouseup = function() {
 setTimeout(function () {
  paste.style.display = 'none';
 }, 0);
};

editor.oncontextmenu = function () {
 paste.setSelectionRange(0, 0);
};