javascript - 使用 contenteditable

标签 javascript css html contenteditable caret

好的,所以我可以很好地编辑我的 DIV 的内容。但是,我正在尝试解决一些问题。

在我的可编辑 div 中,我有一个包含站点地址的 div(例如 twitter.com),我不希望它可以从可编辑 DIV 中删除;它在那里的原因是用户可以复制所有文本,包括域。

如果您删除域以外的所有文本,则插入符号不会显示 - 或者它会一直显示在 DIV 的右侧一秒钟。

如果用户删除域名,它会重新出现,但插入符现在位于它的左侧,我也不想要。

关于使插入符始终可见并将其保持在域右侧的任何解决方案?

哦,出于某种原因,我无法在可编辑 DIV 上使用 onKeyDown 来激活 anylyeText 函数(至少在 JSfiddle 中不行),所以我不得不执行一个 setTimeout 循环。

这是我的 fiddle :jsfiddle


CSS:

.url {
    display: block;
    border: 1px solid rgb(140,140,140);
    padding: 5px;
    box-sizing: border-box;
    color: rgb(35,155,215);
    cursor: text;
    outline: none;
}
.url:focus {
    border-color: rgb(35,155,215);
}

.noedit {
    display: inline;
    color: rgb(140,140,140);
}

HTML:

<div class="url" contenteditable="true" id="textbox"><div class="noedit" contenteditable="false">http://twitter.com/</div>username</div>

JS:

var analyzeText = function() {
    var textbox = document.getElementById('textbox');
    var textVal = textbox.innerHTML;
    var urlString = '<div class="noedit" contenteditable="false">http://twitter.com/</div>';

    if (textVal.length < urlString.length) {
        textbox.innerHTML = urlString;
        textbox.focus();
    }
    setTimeout(function() { analyzeText(); }, 100);
};

(function(){analyzeText();})();

最佳答案

这是一个使用选择和范围的方法。

MDN Selection
MDN Range

(如果您查看 MDN,您会发现不支持 IE9 - 在 IE9 之前,您必须使用专有的 IE 脚本。Google 可以帮助您!)

我做的第一件事是添加这两个变量:

var range = document.createRange();
var sel = window.getSelection();

然后,我像这样修改了你的脚本:

if (textVal.length < urlString.length) {
    textbox.innerHTML = urlString;

    // We create a text node and append to the textbox to select it
    textbox.appendChild(document.createTextNode(''));

    // Text node is selected
    range.setStart(textbox.childNodes[1], 0);

    // Collapse our range to single point (we're not selecting a word, after all!)
    range.collapse(true);

    // Let's clear any selections
    sel.removeAllRanges();

    // Alright, time to position our cursor caret!
    sel.addRange(range);

    textbox.focus();
}

就是这样!这是一个更新的 fiddle 演示:

编辑 - 更新为包含防止用户在域左侧插入文本的逻辑

http://jsfiddle.net/Qycw2/6/

关于javascript - 使用 contenteditable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24377377/

相关文章:

javascript - 如何使特定的键盘输入更改页面上形状的属性?

javascript - 如何通过使用 jquery 单击链接重定向来从其他页面选择/激活某些东西或 div?

javascript - nightwatch自定义命令的执行模型是什么,如何等待它们?

html - Google 字体无法在我的网站上使用

php include 文件也包括这个文件的样式

html - 我的 CSS 背景图片没有显示

javascript - 使用 toggle() 隐藏一个 div

javascript - 如何自动调用System或AMD模块?

Javascript:如何在音频播放器中使用多个播放按钮

css - 如何在不超过尺寸的情况下达到最大尺寸?