我在 html 文档的可编辑区域中创建了内容助手的运行示例。因此,如果用户在键盘上按 ctrl 和空格键,则会出现上下文菜单。目前(参见下面的演示)上下文菜单位于右侧 y 位置(文本下方)。但它不沿着 x 轴(如果文本变长,框将被播种在行的开头)。
你能帮我解决这个问题吗?
问候,神话
示例代码:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Test</title>
<script type="text/javascript">
var iframe = null, iwindow = null, iDocument = null;
function setUpInput() {
iframe = document.createElement( 'iframe' );
iframe.setAttribute( 'id', 'iframe-test' );
iframe.setAttribute( 'frameborder', 0 );
iframe.setAttribute( 'style', 'width:100%; height:100%;border: solid 1px red;' );
document.getElementById( "input" ).appendChild( iframe );
iwindow = iframe.contentWindow;
idocument = iwindow.document;
idocument.open();
idocument.write("<p></p>");
idocument.close();
idocument.body.setAttribute( 'spellcheck', false );
idocument.body.setAttribute( 'style', 'font-family: Consolas,serif;font-size: 0.8em;' );
idocument.body.contentEditable = true;
iwindow.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode == 32) {
createSuggestObject();
return false;
}
if (e.ctrlKey) return false;
};
iwindow.onkeypress = function(e) {if (e.ctrlKey) return false;};
}
function createSuggestObject() {
suggest = new Object();
suggest.box = document.createElement( 'div' );
suggest.box.style.position = 'absolute';
suggest.box.style.width = '120px';
suggest.box.style.overflow = 'auto';
suggest.box.style.border = '1px solid #BEC7E4';
suggest.box.style.display = 'block';
suggest.box.style.marginTop = '16px';
suggest.box.innerHTML = "Example 1";
document.body.appendChild( suggest.box )
var position = iframe.getBoundingClientRect();
var selObj = iwindow.getSelection();
var selRange = selObj.getRangeAt(0);
var p2 = selObj.anchorNode.parentNode.getBoundingClientRect();
suggest.box.style.top = Math.round( window.scrollY + position.top + p2.top) + 'px';
suggest.box.style.left = Math.round( window.scrollX + position.left + p2.left) + 'px';
}
window.onload = function() {
setUpInput();
};
</script>
</head>
<body>
<div id="input"></div>
</body>
</html>