纯JavaScript实现运行代码、复制代码和保存代码的功能(后两个功能受限浏览器)

2016-01-04 21:21:33  访问(1788) 赞(0) 踩(0)

  • <script language="javascript" type="text/javascript">
    
        //运行代码
        function runEx() {
            // asp.net控件txt_Input对应的网页ID txt_Input.ClientID //
            var ctrlId = "<%=txt_Input.ClientID %>";
            var cod = document.getElementById(ctrlId);
    
            if (cod == null) {
                alert("没有找到控件");
                return;
            }
    
            var code = cod.value;
            
            if (code != "") {
                var newwin = window.open('', '', '');
                newwin.opener = null
                newwin.document.write(code);
                newwin.document.close();
            }
        }
        
        //复制代码
        function doCopy() {
            if (document.all) {
                // asp.net控件txt_Input对应的网页ID txt_Input.ClientID //
                var ctrlId = "<%=txt_Input.ClientID %>";
                var textRange = document.getElementById(ctrlId).createTextRange();
                textRange.execCommand("Copy");
                alert("代码已经复制到剪切板");
            }
            else {
                // IE高级版本也失效 //
                alert("此功能只能在IE上有效\n\n请在文本域中用Ctrl+A选择再复制")
            }
        }
        
        //另存代码
        function saveCode() {
            // asp.net控件txt_Input对应的网页ID txt_Input.ClientID //
            var ctrlId = "<%=txt_Input.ClientID %>";
            var cod = document.getElementById(ctrlId)
            var winname = window.open('', '', 'width=0,height=0,top=1,left=1');
            winname.document.open('text/html', 'replace');
            winname.document.write(cod.value);
            winname.document.execCommand('saveas', '', 'Code.htm');
            winname.close();
        }
    </script>
    


上一条:

下一条:


 

相关评论

评论加载中……
 

发表评论

类型:
内容:
  (Alt+Enter)