我正在开发一个图形用户界面工具,可以在其中选择、拖动文本框并编辑内容。想想在 powerpoint 等绘图程序中进行文本编辑。我对文本选择有一些非常具体的要求。我需要确保在其中一个框中选择文本时,所选内容不会扩展到其他相邻框中的文本。
好消息是有办法做到这一点,坏消息是它只适用于 IE,我需要为 Chrome 找到解决方法。
Supported only in Internet Explorer. Enables selection to start within the element; however, the selection will be contained by the bounds of that element.
我猜测解决方法需要做一些事情,比如监听 selectstart 和 selectchange 事件,调用 preventDefault(),以及手动操作选择对象。
任何想法表示赞赏;)
更新:这是一个fiddle这主要是有效的。错误是,我需要以某种方式阻止 Ctrl-A,并且在窗口外选择和释放鼠标会使其他文本暂时无法选择。不知道如何解决这些问题,有人吗?提示风滚草...
HTML
<div id="one" class="textbox">qwe qweqwe <b>werwesd ewrwer</b> fsdfdsrwe fdsfsdf erertre fsdfsdf</div>
<div id="two" class="textbox">dsgdfs dfgdsf dfgdfg dfgdfs <i>dfsgsdf</i> dfsgdfsg</div>
CSS
.textbox {
position: absolute;
-webkit-user-select: text;
width: 250px;
font-size: 30px;
border: 1px solid black;
}
#one { left: 150px; top: 150px; }
#two { left: 450px; top: 250px; }
JS
document.addEventListener('mousedown', mousedown, false);
document.addEventListener('mouseup', mouseup, false);
// While selecting disallow selection of other text.
function mousedown(event) {
console.log('mousedown', event.target);
var current = findParentTextBox(event.target);
var list = document.querySelectorAll('.textbox');
for (var i = 0, textbox; textbox = list[i]; i++) {
if (textbox != current) {
textbox.style.webkitUserSelect = 'none';
}
}
}
// Once finished selecting allow all text to be selected again.
function mouseup(event) {
console.log('mouseup', event.target);
var list = document.querySelectorAll('.textbox');
for (var i = 0, textbox; textbox = list[i]; i++) {
textbox.style.webkitUserSelect = 'text';
}
}
function findParentTextBox(node) {
while (node != null) {
if (node.className == 'textbox')
return node;
node = node.parent;
}
return null;
}
编辑:
提交了一个 chrome 错误:https://code.google.com/p/chromium/issues/detail?id=346533
最佳答案
不确定它是否会干扰您的其他交互需求(拖动需要测试),但 iframe 可能适合您。它们具有开箱即用的您想要的选择行为(包括全选)。您必须使用 javascript 或来自外部资源来填充它们。 这是带有 iframe 的 jsfiddle(使用 js 从 div 创建 iframe): http://jsfiddle.net/5y8EA/3/
对于可编辑的文本,可以勾选contenteditable
属性:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_Editable
关于javascript - Google Chrome 浏览器的 "user-select: element"解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21983071/