运行代码预览代码,代码另存为,复制代码功能的实现

 
更多

一些以展示html特效的网站经常会在具体页面加一个运行代码这样的一个效果,即特效代码在textarea文本框内,下面有一个运行代码按钮,点击运行按钮,就直接运行了textarea内的代码。下面和大家分享一个这样的案例,其实这个挺简单的。

首先截图展示一下本示例的效果:

运行代码预览代码,代码另存为,复制代码功能示例效果图

下面这段代码示例同时实现了预览代码,代码另存为和复制代码两个功能,注意这里的代码另存为,复制代码仅支持IE浏览器。

<html xmlns="http://www.phpernote.com/javascript-function/38.html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js实现运行代码的预览功能</title>
</head>
<body>
<textarea id="codeContent" rows="9" cols="50">
在这里输入要运行的代码
</textarea>
<br>
<input type="button" onclick="runCode()" value="运行代码" />
<input type="button" onclick="copyCode()" value="复制代码" />
<input type="button" onclick="saveCode()" value="代码另存为" />
<script language="javascript">
var obj=document.getElementById('codeContent');
function runCode(){
	var code=obj.value;
	var newWindow=window.open('','','');
	newWindow.opener=null;
	newWindow.document.write(code);
	newWindow.document.close();
}
function saveCode(){
	var code=obj.value;
	var winname=window.open('','_blank','top=10000');
	winname.document.open('text/html','replace');
	winname.document.writeln(code);
	winname.document.execCommand('saveas','','phpernote.html');
	winname.close();
}
function copyCode(){
	if(isIE()){
		alert('代码已复制到剪贴板!');
	}else{
		alert('本页面复制功能仅支持IE浏览器!');
		return false;
	}
	var rng=document.body.createTextRange();
	rng.moveToElementText(obj);
	rng.scrollIntoView();
	rng.select();
	rng.execCommand("Copy");
	rng.collapse(false);
}
function isIE(){
	var Sys={};
	var ua=navigator.userAgent.toLowerCase();
	var s;
	(s=ua.match(/msie ([\d.]+)/))?Sys.ie=s[1]:false;
	return Sys.ie;
}
</script>
</body>
</html>
打赏

本文固定链接: https://www.cxy163.net/archives/3919 | 绝缘体

该日志由 绝缘体.. 于 2013年08月07日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: 运行代码预览代码,代码另存为,复制代码功能的实现 | 绝缘体
关键字: , , , ,

运行代码预览代码,代码另存为,复制代码功能的实现:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter