简体   繁体   English

我如何将javascript中的html设置为元素中的特定位置

[英]How can i set html in javascript to specific location in element

I have a div just like this 我有一个像这样的div

<div contenteditable="true" >
 Hello this is content editable.... [cursor is blinking here] and more text
</div> 

How can i set a data where cursor is blinking. 如何设置光标闪烁的数据。

Thanks in advance. 提前致谢。

You use execCommand with the insertHTML command: 您可以将execCommandinsertHTML命令一起使用:

document.execCommand("insertHTML", false, "the HTML to insert");

Live Example: 现场示例:

 $("div").on("keydown", function(e) { if (e.ctrlKey && e.which == 81) { document.execCommand("insertHTML", false, "<strong>inserted</strong>"); return false; } }); 
 <p>Put your cursor in the relevant location below, then press Ctrl+Q:</p> <div contenteditable="true"> Hello this is content editable.... and more text </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

Sadly this doesn't seem to work on IE11. 可悲的是,这似乎不适用于IE11。 :-| :-| For cross-browser support, you might look at Tim Down's rangy library . 对于跨浏览器的支持,您可以查看Tim Down的rangy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在这种特定情况下,如何使用 javascript 删除 HTML 元素 - How can I remove an HTML element using javascript in this specific situation 如何使用 JavaScript 将焦点设置在 HTML 表单中的元素上? - How can I set focus on an element in an HTML form using JavaScript? 如何设置 HTML 的默认值<select>元素与 JavaScript? - How can I set the default value for an HTML <select> element with JavaScript? 如何将元素的高度设置为 HTML 元素的实际所需高度,而不是 CSS 或 JavaScript 中的 auto? - How can I set the height of element to the actual required height of an HTML element, as opposed to auto in CSS or JavaScript? 如何使用 JavaScript 获取元素的 HTML? - How can I get the HTML for an element with JavaScript? 如何使用 javascript 根据其类型访问特定的 HTML 元素? - How can i access specific HTML element based on its type using javascript? 如何通过javascript(jquery)将html元素的内容设置为php include文件 - how can I set the content of a html element via javascript (jquery) to php include file 如何在 Javascript 集合 object 中的特定索引处添加元素? - How do I add an element at a specific index in Javascript set object? 如何从 html 中提取特定元素 - how can i extract a specific element from the html 如何在数组的特定元素上设置加载 state? - How can I set a loading state on a specific element of an array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM