在html中嵌入js运行框简单示例
2011-03-16 10:11 ☆冷枫☆ 阅读(1164) 评论(1) 编辑 收藏 举报作为一个coder,通常会编写javascript脚本,为了方便在页面内直接查看测试结果最好有个可以运行的文本框。我们在园子里面也经常可以看见研究js的博客中嵌入了一个文本输入框,点击运行按钮可以查看js效果。其实实现这个并不是很难,几个js方法就搞定。如下所示:
首先我们来看运行代码如何实现:
//执行代码
function runCode(obj) {
var winname = window.open('', "_blank", '');
var content = document.getElementById(obj).value;
winname.document.open('text/html', 'replace');
winname.opener = null
winname.document.writeln(content);
winname.document.close();
}
function runCode(obj) {
var winname = window.open('', "_blank", '');
var content = document.getElementById(obj).value;
winname.document.open('text/html', 'replace');
winname.opener = null
winname.document.writeln(content);
winname.document.close();
}
复制代码实现方法如下:
//复制代码
function doCopy(obj)
{
var codeObj = document.getElementById(obj);
clipboardData.setData('text', codeObj.innerText);
alert('已经复制代码');
}
function doCopy(obj)
{
var codeObj = document.getElementById(obj);
clipboardData.setData('text', codeObj.innerText);
alert('已经复制代码');
}
保存代码实现方法如下:
// 另存为文件
function doSave(obj, filename)
{
var win = window.open('', '_blank', 'top=10000');
var code = document.getElementById(obj).innerText;
win.opener = null;
win.document.write(code);
win.document.execCommand('saveas', true, filename);
win.close();
}
function doSave(obj, filename)
{
var win = window.open('', '_blank', 'top=10000');
var code = document.getElementById(obj).innerText;
win.opener = null;
win.document.write(code);
win.document.execCommand('saveas', true, filename);
win.close();
}
最后一步就是在按钮点击事件中调用上述事件了:
<textarea style="width: 450; height: 300" id="theCode" title="双击运行代码" ondblclick="runCode('theCode');">请输入要运行的html代码
</textarea><br />
<input onclick="runCode('theCode')" value="运行代码" type="button">
<input onclick="doCopy('theCode')" value="复制代码" type="button">
<input onclick="doSave('theCode','test.cs')" value="保存代码" type="button">
</textarea><br />
<input onclick="runCode('theCode')" value="运行代码" type="button">
<input onclick="doCopy('theCode')" value="复制代码" type="button">
<input onclick="doSave('theCode','test.cs')" value="保存代码" type="button">
励志博客园--优秀的阅读、励志、交流学习平台。您的网上心灵家园!