javascript - Google Chrome 浏览器的 "user-select: element"解决方法?

标签 javascript css google-chrome

我正在开发一个图形用户界面工具,可以在其中选择、拖动文本框并编辑内容。想想在 powerpoint 等绘图程序中进行文本编辑。我对文本选择有一些非常具体的要求。我需要确保在其中一个框中选择文本时,所选内容不会扩展到其他相邻框中的文本。

好消息是有办法做到这一点,坏消息是它只适用于 IE,我需要为 Chrome 找到解决方法。

user-select: element

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/

相关文章:

android - HTML5 音频不适用于 Android 4.4 上的 Crosswalk Cordova 或基于标准 Cordova 的 WebView

javascript - 如何在两个不同的列中显示 map 结果

javascript - d3.js - 使用 .selectAll() 根据属性值选择 Node 元素

javascript - 该网站如何禁用内容选择?

html - 我的按钮的文字没有调整大小?

css - Chrome/Safari无法填充Flex父级的100%高度

javascript - 哪些 JavaScript 库具有以下控件

javascript - 星级 CSS 问题

html - Internet Explorer 11 使用边框半径模糊背景图像

javascript - 如何阻止或编辑 native 浏览器表单弹出窗口/警报?