上传js,js修改html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传js文件</title>
    <style>
        div{
            width: 200px;
            height: 150px;
            background: yellow;
                    }
    </style>
</head>
<body>
    <input type="file">
    <div></div>
    <script>
        //获取上传的文件
        var fl = document.querySelector("input");
        fl.onchange=function(){
            var file = fl.files[0];
            //创建读取文件的对象
            var fRead = new FileReader();
            fRead.readAsText(file);//读取文件
            //文件加载的事件
            fRead.onload=function(){
                //读取文件的结果(读文件中都是js的代码,在script标签中)
                var txtJS = this.result;
                //创建script标签,并加入到head标签中
                var st = document.createElement("script");
                st.innerHTML = txtJS;//把js代码放在script标签中
                //把script标签加入到head标签中
                document.querySelector("head").appendChild(st);
            }
        }
    </script>
</body>
</html>

上传的txt.js

var div1 = document.querySelector("div");
div1.onclick = function(){
    div1.style.width = '300px';
    div1.style.height ='500px';
    div1.style.background="red";
}

实现的效果:

上传前:

上传成功后点击

 

posted @ 2019-01-04 17:21  quitpoison  阅读(354)  评论(0编辑  收藏  举报