JS Method of Implementing Cursor Position Insertion in iframe Editor of Compatible with IE and Firefox

  • 2021-06-29 10:18:54
  • OfStack

This article shows an example of how JS implements cursor position insertion in the iframe editor.Share it for your reference, as follows:


<html>
<iframe id="x" name="x"></iframe>
<input type="button" onclick="t()" value="test">
<input type="button" onclick="frames['x'].location.href='about:blank';" value="clear">
<script>
//setTimeout('window.frames["x"].document.designMode="On"',200);
function t(){
window.frames["x"].document.designMode="On";
var html = '<b style="color:red">'+$('xx').value+'</b>';// Inserted Content (html) Can be a picture. 
if(getBrowser()=='ie'){
var Editor = window.frames["x"];//IE Obtain iframe Method, otherwise the picture position runs to the top of the page. 
Editor.focus();
o=Editor.document.selection.createRange();
o.pasteHTML(html);
}else if(getBrowser()=='chrome'){
var Editor = $('x');//firefox Get nodes this way 
Editor.focus();
//alert(Editor.contentWindow.getSelection().getRangeAt(0));
var rng = Editor.contentWindow.getSelection().getRangeAt(0);
var frg = rng.createContextualFragment(html);
rng.insertNode(frg);
}
}
// Get Browser Version 
function getBrowser(){
var agentValue = window.navigator.userAgent.toLowerCase();
if(agentValue.indexOf('msie')>0){
return "ie";
}else if(agentValue.indexOf('firefox')>0){
return "ff";
}else if(agentValue.indexOf('chrome')>0){
return "chrome";
}
}
function $(id){
return document.getElementById(id);
}
// According to element className Attribute gets the element, if more than one element style class name is the same, you can use index Specifies the number of elements to return, and 1 Are 1
function getNodeByClassName(vclassname,index){
//var allnodes = document.all;
var allnodes = document.getElementsByTagName("*");
var x = 0;
for(var i=0;i<allnodes.length;i++){
if(allnodes[i].className==vclassname){
if(index!="undefined"){
x++;
if(x<index){
continue;
}
}
return allnodes[i];
}
}
}
</script>
 Input:  <input id="xx">

More readers interested in JavaScript-related content can view this site's topics: json Operation Skills Summary in JavaScript, JavaScript Switching Special Effects and Skills Summary, JavaScript Find Algorithmic Skills Summary, JavaScript Animation Special Effects and Skills Summary, JavaScript Errors and Debugging Skills Summary, JavaScript Data Structure and Algorithmic Skills Summary,Summary of JavaScript Traversal Algorithms and Techniques and Summary of JavaScript Mathematical Operation Usage

I hope that the description in this paper will be helpful to everyone's JavaScript program design.


Related articles: