我需要以一种可以从任何地方调用它的方式来安排此代码

时间:2017-08-30 11:01:28

标签: javascript

我有这个在DOM加载后立即运行的JavaScript函数。它尝试获取拖放字段的元素,尽管它尚不可用导致空错误。因此,如果我的拖放是模式或在系统启动时未加载的任何其他页面中,我无法使用此功能。

我目前的解决方案是加载一个隐藏的拖放字段,但我需要一个更灵活的解决方案,我可以从任何地方实现它。我需要阻止它立即运行网站加载并通过像丢弃或加载这样的事件触发它,这样它将运行整个网站。我试图重新安排它,但代码太乱了,因此认为原始的很容易让你理解。我知道jquery更容易,但我需要使用vanilla javascript

(function() {

  // getElementById
  function $id(id) {
    return document.getElementById(id);
  }

  // file drag hover
  function FileDragHover(e) {
    e.stopPropagation();
    e.preventDefault();
    e.target.className = (e.type == "dragover" ? "hover" : "");
  }


  // file selection
  function FileSelectHandler(e) {

    // cancel event and hover styling
    FileDragHover(e);

    // fetch FileList object
    var files = e.target.files || e.dataTransfer.files;

    // process all File objects
    for (var i = 0, f; f = files[i]; i++) {
      UploadFile(f);
    }

  }



  // output file information
  function ParseFile(file) {

    var iconpath = "";
    var size = 0;
    var units = "";

    if (file.type == "application/pdf") {
      iconpath = "<img src='resources/dragdrop/pdf.png' style='width:50px;height:50px;'>";
    } else {
      iconpath = "File Information:";
    }

    if (file.size > 1048576) {
      size = file.size / 1024 / 1024;
      units = "MB";
    } else {
      size = file.size / 1024;
      units = "KB";
    }


    return "<td class='dragtd'>" + iconpath + "</td><td class='dragtd'>" + file.name + "</td><td class='dragtd'>" + file.type + "<td class='dragtd'>" + size.toFixed(2) + "" + units + "</td>";
  }


  // upload JPEG files
  function UploadFile(file) {

    // following line is not necessary: prevents running on SitePoint servers
    if (location.host.indexOf("sitepointstatic") >= 0)
      return

    var xhr = new XMLHttpRequest();
    if (xhr.upload) {

      // create progress bar
      var o = $id("messages");
      var k = $id("progress");
      var step = k.appendChild(document.createElement("z"));
      var content = o.appendChild(document.createElement("tr"));
      var progress = k.appendChild(document.createElement("p"));
      progress.appendChild(document.createTextNode("Waiting to upload"));
      // progress bar
      xhr.upload.addEventListener("progress",
        function(e) {
          var pc = parseInt(e.loaded / e.total * 100);
          progress.style.width = pc + "%";
          progress.innerHTML = pc + "% " + file.name;
          if (pc == 100) {
            content.innerHTML = ParseFile(file);
            k.removeChild(progress);
          } else {

          }
        },
        false
      );

      // file received/failed
      xhr.onreadystatechange = function(e) {
        if (xhr.readyState == 4) {
          progress.className = (xhr.status == 200 ? "success" : "failure");
        }
      };
      //make multipart
      var formData = new FormData();
      formData.append("thefile", file);

      // start upload
      xhr.open('POST', '/resources/dragdrop/upload.jsp?action=save', true);
      //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.onreadystatechange = function() {
        try {
          if (xhr.readyState == 4) {
            if (xhr.status == 200) {
              var respText = xhr.responseText.replace(/^\s+|\s+$/g, "");
              loadPageInDiv('resources/dragdrop', 'files.jsp', 'fileviewdiv')
            } else {
              alert("error hatujui");
            }
          }
        } catch (e) {
          alert(e);
        }
      };
      xhr.send(formData);
      ParseFile(file);
    }

  }


  // initialize
  function Init() {

    var fileselect = $id("fileselect"),
      filedrag = $id("filedrag"),
      submitbutton = $id("submitbutton");

    // file select
    fileselect.addEventListener("change", FileSelectHandler, false);

    // is XHR2 available?
    var xhr = new XMLHttpRequest();
    if (xhr.upload) {

      // file drop
      filedrag.addEventListener("dragover", FileDragHover, false);
      filedrag.addEventListener("dragleave", FileDragHover, false);
      filedrag.addEventListener("drop", FileSelectHandler, false);
      filedrag.style.display = "block";

      // remove submit button
      submitbutton.style.display = "none";
    }

  }

  // call initialization file
  if (window.File && window.FileList && window.FileReader) {
    Init();
  }


})();

0 个答案:

没有答案