首页 > 解决方案 > Highlight a div element in a content editable input as if it was text

问题描述

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!

标签: htmlcsscontenteditable

解决方案


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>


推荐阅读