触发输入文件在首页加载时点击模式不会触发

时间:2018-09-27 09:33:04

标签: javascript angularjs file-upload

使用angularJS,我有一个模式,该模式应触发输入文件以上传文件。

这是触发点击的功能

function triggerUploadMethod()
{
    inputFile = document.createElement('input');
    inputFile.type = 'file';
    inputFile.onchange = photoChosen;
    inputFile.click();
}

让我感到无聊的是,在第一个页面加载中,当我打开模式时,触发器没有被触发。如果我关闭模式并再次打开,触发器将起作用,并且它将一直工作到下一页加载为止。。。。

这仅在Chrome上发生。在Firefox,Edge和Internet Explorer上,即使页面加载后,触发器也每次都起作用...

1 个答案:

答案 0 :(得分:0)

作为免责声明,我从未使用过Angular,并且由于您未提供其他任何代码,因此我使用了香草JavaScript。

据我所知,代码中的错误并非来自您上面发布的错误。在下面的代码段中,我从W3Schools How to Make a Modal Box With CSS and JavaScript中获取了代码,然后将您的函数添加到了单击按钮即可打开模态的部分,并且工作正常(我在Chrome上)。

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// This variable isn't defined in your code so I just assume
// it's somewhere at the top.
var inputFile;

// When the user clicks on the button, open the modal.
// Also creates your input and clicks it.
btn.onclick = function() {

    modal.style.display = "block";
    
    triggerUploadMethod();
    
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

// Create the input element and click it.
function triggerUploadMethod() {

  inputFile = document.createElement('input');
  inputFile.type = 'file';
  
  // I have no idea what this is so I can't include it.
  //inputFile.onchange = photoChosen;
  
  inputFile.click();

}
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>

</div>