asp和javascript实现的在线运行代码,和复制代码的代码,通常用来在写入数据库之前或者展示当前代码效果所用到,写入数据库之前如果效果不如意,可以先修改,再运行,再修改 ……,直到修改的效果满意为止,然后再提交到数据库中去,这样就避免了多次打开修改页去修改,省去许多时间。
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>代码运行</title>
<style type="text/css">
/* 运行代码 */
.RunCodes {clear:both;width:500px; height:180px;margin:10px 0;}
.RunCodes textarea{overflow-x:hidden;overflow-y:auto;border:1px solid #9FC3DB; padding:3px;width:500px; height:150px;}
.RunCodes input{float:left; border:1px solid #CDCCB4;background-color: #EFEEE1;width:80px; margin:1px 5px 0 0;padding:5px 10px 3px !important;padding:3px 10px 0px;}
.RunCodes span{float:left;margin:5px 0 0 5px;font-size: 14px;}
</style>
</head>
<body>
<%
Function content_Code(Str)
dim ary_String,i,n,n_pos
ary_String=split(Str,"[code ]")
n=ubound(ary_String)
If n<1 then
content_Code=Str
Exit function
End If
for i=1 to n
n_pos=inStr(ary_String(i),"[ /code]")
If n_pos>0 then
ary_String(i)="<br /><div class=""RunCodes""><textarea id=runcode"&i&" name=runcode"&i&">" & server.HTMLEncode(left(ary_String(i),n_pos-1))&"</textarea><br /><input type=button value=运行代码 onclick=runCode(runcode"&i&")><input type=button value=复制代码 onclick=copycode(runcode"&i&")><span>提示:您可以先修改部分代码再运行</span></div><br />" & _
right(ary_String(i),len(ary_String(i))-n_pos-6)
Else
ary_String(i)="[code ]" & ary_String(i)
End if
next
content_Code=join(ary_String,"")
End Function
%>
<script language="javascript">
function runCode(obj)
{
var winname = window.open('', "_blank", '');
winname.document.open('text/html', 'replace');
winname.opener = null
winname.document.writeln(obj.value);
winname.document.close();
}
function copycode(obj)
{
var rng = document.body.createTextRange();
rng.moveToElementText(obj);
rng.scrollIntoView();
rng.select();
rng.execCommand("Copy");
rng.collapse(false);
alert("代码已经复制到剪切板");
}
</script>
<%=content_Code("[code ]<a href=""http://www.aspprogram.cn"" target=""_blank"">asp编程网</a>[ /code]fadfasdfasdf[code ]<script language=""javascript"">alert('如此简单');</script>[ /code]")%>
</body>
</html>