首页 > 解决方案 > 获取可编辑 div 中选定元素的 id

问题描述

我正在做一个编码项目。它是一个在线文本编辑器。我希望人们能够更改他们选择的元素(文本)的颜色,以便我可以更改 CSS。我该怎么做?(只需获取所选元素的 id 或其他任何内容)我被困在如何实际判断哪个元素被突出显示。每当我尝试查找它时,所有结果都与select元素有关。就像是document.getElementByCursor

我的项目

标签: javascripthtmlcssdom

解决方案


我希望这个样本足以满足您的需求。您可以在此处查看基本解决方案并针对您的特定需求进行升级/更新。如果它对你来说足够好,请投票给这个答案。

document.getElementById("update_colour").onclick = function() {
  // Get Selection
  sel = window.getSelection();
  if (sel.rangeCount && sel.getRangeAt) {
    range = sel.getRangeAt(0);
  }
  // Set design mode to on
  document.designMode = "on";
  if (range) {
    sel.removeAllRanges();
    sel.addRange(range);
  }
  
  var dd = document.getElementById("colour_dd");
  var strUser = dd.options[dd.selectedIndex].value;
  
  // Colorize text
  document.execCommand("ForeColor", false, strUser);
  // Set design mode to off
  document.designMode = "off";
}
<span id="editable_div" contenteditable>
Plaid everyday carry trust fund tofu, twee messenger bag meh cronut waistcoat. Celiac hashtag 90's pour-over literally, hexagon trust fund master cleanse. Fam raclette ramps biodiesel succulents. Squid pork belly coloring book biodiesel cray. Typewriter ugh poutine semiotics thundercats vape, yr YOLO. Distillery stumptown VHS, gentrify knausgaard vegan franzen microdosing chambray forage selvage. Af hell of hammock pabst neutra pour-over tofu fashion axe.
</span>
<br/><br/>
<select id="colour_dd">
  <option value="red">Red</option>
  <option value="blue">Blue</option>
  <option value="green">Green</option>
</select>
<br/><br/>

<button id="update_colour">Update Selected Text Color</button>


推荐阅读