javascript - 获取可编辑 div 中选定元素的 id
问题描述
我正在做一个编码项目。它是一个在线文本编辑器。我希望人们能够更改他们选择的元素(文本)的颜色,以便我可以更改 CSS。我该怎么做?(只需获取所选元素的 id 或其他任何内容)我被困在如何实际判断哪个元素被突出显示。每当我尝试查找它时,所有结果都与select
元素有关。就像是document.getElementByCursor
解决方案
我希望这个样本足以满足您的需求。您可以在此处查看基本解决方案并针对您的特定需求进行升级/更新。如果它对你来说足够好,请投票给这个答案。
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>
推荐阅读
- excel - Excel 将一维数组转置为多维数组
- python - 检查是否包含字符串时获得完全匹配是行
- android-uiautomator - 如何计算 UiAutomator 中所有 RecyclerView 项目的不同项目
- python - 唯一约束失败:“app”_customuser.username
- javascript - 强制将块拆分为某个包
- django - 多个附件django电子邮件
- linq - 实体框架查询单个查询中的相关实体
- c# - 获取当前 AD 域加入信息的最可靠方法是什么?(DsRoleGetPrimaryDomainInformation,?)
- c - 如何将数组的最后一个元素设置为某个数字?
- sql - 从 MS Access 中的子查询中检索多个值