gpt4 book ai didi

javascript - 使用 contenteditable

转载 作者:太空宇宙 更新时间:2023-11-04 13:16:25 26 4
gpt4 key购买 nike

好的,所以我可以很好地编辑我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com