帖子的最终更新以及最后的目标成就。有输入字段。需要用文本显示包含
img
和不可显示 span
的块。下面的片段完成了任务。但它有错误。我无法更改 contenteditable
,因为它属于外部站点,并且我的代码在浏览器扩展中运行。
运行片段。单击行尾,按左箭头按钮几次。您的光标从图像移动到文本。没关系。现在按右箭头按钮并尝试到达行尾。当光标到达第一个图像时,光标的选择消失。换句话说,我们可以从右到左移动光标,但从左到右则失败。
.editor {
display: inline-block;
width: 200px;
}
.hide {
display: none;
}
<div class="editor" contenteditable="true">text <span contenteditable="false"><span class="hide"> DogePls </span><img alt="DogePls" src="https://cdn.betterttv.net/emote/55c7eb723d8fd22f20ac9cc1/1x.webp"></span><span contenteditable="false"><span class="hide"> DogePls </span><img alt="DogePls" src="https://cdn.betterttv.net/emote/55c7eb723d8fd22f20ac9cc1/1x.webp"></span><span contenteditable="false"><span class="hide"> DogePls </span><img alt="DogePls" src="https://cdn.betterttv.net/emote/55c7eb723d8fd22f20ac9cc1/1x.webp"></span></div>
如果图像之间有任何符号,错误修复。但我不需要那里的符号。因为输入字段是聊天的消息发送器,用户可以在任何地方输入。
我尝试添加伪元素,错误仍然重现。
span[contenteditable=false]:after {
content: "space";
}
我不相信内容在这种情况下会起作用,因为:
‘ 使用 CSS content 属性插入的对象是匿名替换元素。它们是“匿名的”,因为它们不存在于 HTML 标记中。’
(来自 MDN)所以我们永远不会让替换的跨度可删除。
因此,这是一种使用背景图像并将字体大小设置为您希望表情符号与周围文本相关的任何大小的方法。
<div contenteditable=true>
3) span tag with background-image:
<span contenteditable=false style="display: inline-block; font-size: 2em; background-image: url(https://cdn.betterttv.net/emote/58d2e73058d8950a875ad027/1x); background-size: contain; background-repeat: no-repeat; background-position: center center; text-align: right;"> </span>
</div>
更新:需要保留 DOM 中 span 元素中的文本,但不要使其可见(从这个意义上说,它被图像替换 - 但如上所述,这不会让我们做正确的事情)事情编辑明智)。
我不确定我是否推荐下面的代码片段,它看起来很繁琐,因此可能容易脆弱,但是如果它在需要它的特定上下文中有用,我将其包含在内。基本上,它将文本保留在跨度中,但通过将跨度的宽度和高度固定为表情符号所需的内容来“替换”它,隐藏溢出文本并通过在顶部放置一个 before 伪元素来伪装剩余文本表情符号图像作为背景。
注意:不可能使文本透明(或字体大小为0),这是我最初的想法,因为插入符号随后消失了。
<style>
div span {
--size: 28px;
/* set to whatever you want the size of the emoji to be */
}
div span::after {
content: '';
z-index: 1;
position: absolute;
top: 0;
left: 0;
width: var(--size);
height: var(--size);
background-image: url(https://cdn.betterttv.net/emote/58d2e73058d8950a875ad027/1x);
background-size: contain;
background-repeat: no-repeat;
background-position: center center;
background-color: white;
}
</style>
<div contenteditable=true style="position: relative;">
3) span tag with background-image:
<span contenteditable=false style="width: var(--size); height: var(--size); display: inline-block; color: black; overflow: hidden; white-space: nowrap; text-align: right; position: relative; margin-right: 1px;">Wowee</span>.
</div>
这可能有帮助:
<div contenteditable=true>
span tag:
<span style="content: url(https://cdn.betterttv.net/emote/58d2e73058d8950a875ad027/1x)">Wowee</span>
</div>
您只需要在跨度后单击一些可选区域即可添加它,或者您可以使用 css(填充等)来做到这一点。
我不知道它为什么有效(Chrome),但你看:
(顺便说一句,在 Firefox 中,您的所有 3 个示例都可以工作,您需要按退格键 3 次,但它们确实可以)
<div contenteditable>
3) span tag with "#8203":
<span style="content: url(https://cdn.betterttv.net/emote/58d2e73058d8950a875ad027/1x)"></span>
​
</div>
(我不建议使用
contenteditable
,因为它充满了错误和意外行为,因此我认为尝试了解发生了什么是没有意义的)