突出显示内容可编辑输入中的div元素,就像它是文本一样(Highlight a div element in a content editable input as if it was text)

我目前有一个JS小提琴在内容可编辑输入中显示带背景图像的div。 我希望能够突出显示div,就好像它是文本一样。

.input {
  border: 1px solid black;
  width: 200px;
}

.emoji {
  width: 16px;
  height: 16px;
  background-size: contain;
  display: inline-block;
  background-image: url(https://twemoji.maxcdn.com/2/72x72/1f609.png);
} 
  
<div contenteditable="true" class="input">
    <div class='emoji'/>
</div> 
  
 

注意上面的小提琴试图用鼠标突出显示表情符号,好像它是文本不会正确地突出显示表情符号。

我已经尝试了以下两种解决方案,但他们没有工作。

1)在emoji div上设置一个tab-index="-1" ,并添加下面的css来设置背景颜色以突出显示表情符号

.emoji { &:focus { background-color: #338fff; } }

2)使用::selected CSS并设置背景颜色使其看起来突出显示

.emoji { &:selected { background-color: #338fff; } }

任何帮助表示赞赏!

I current have the following JS Fiddle showing a div with a background image in a content editable input. I would like to be able to highlight the div as if it were text.

.input {
  border: 1px solid black;
  width: 200px;
}

.emoji {
  width: 16px;
  height: 16px;
  background-size: contain;
  display: inline-block;
  background-image: url(https://twemoji.maxcdn.com/2/72x72/1f609.png);
} 
  
<div contenteditable="true" class="input">
    <div class='emoji'/>
</div> 
  
 

Notice how in the fiddle above attempting to highlight the emoji with the mouse as if it were text does not highlight the emoji properly.

I have tried the following 2 solutions but they have not worked.

1) Setting a tab-index="-1" on the emoji div and adding the following css to set the background color to make the emoji look highlighted

.emoji { &:focus { background-color: #338fff; } }

2) Using the ::selected css and setting the background color to make it look highlighted

.emoji { &:selected { background-color: #338fff; } }

Any help is appreciated!

最满意答案

将emoji div更改为图片标签并将其链接到透明源。

#input {
  border: 1px solid black;
  width: 200px;
}

.emoji {
  width: 16px;
  height: 16px;
  background-size: contain;
  display: inline-block;
  background-image: url(https://twemoji.maxcdn.com/2/72x72/1f609.png);
} 
  
<div contenteditable="true" id="input">
  <img src="http://upload.wikimedia.org/wikipedia/commons/c/ce/Transparent.gif" class="emoji"/>
</div> 
  
 

Change the emoji div to an image tag and link it to a transparent source.

#input {
  border: 1px solid black;
  width: 200px;
}

.emoji {
  width: 16px;
  height: 16px;
  background-size: contain;
  display: inline-block;
  background-image: url(https://twemoji.maxcdn.com/2/72x72/1f609.png);
} 
  
<div contenteditable="true" id="input">
  <img src="http://upload.wikimedia.org/wikipedia/commons/c/ce/Transparent.gif" class="emoji"/>
</div> 
  
 

更多推荐