首页 > 解决方案 > 在第一页加载时触发输入文件点击模式不会触发

问题描述

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

这是触发点击的函数

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

让我感到无聊的是,在第一次页面加载时,当我打开模式时,触发器没有被触发。如果我关闭模式并再次打开,触发器将工作,它将继续工作,直到下一页加载...在第一页加载时无法正常工作会发生什么?

这只发生在 Chrome 上。在 Firefox、Edge 和 Internet Explorer 上,触发器每次都有效,即使在页面加载后...

标签: javascriptangularjsfile-upload

解决方案


作为免责声明,我从未使用过 Angular,并且由于您没有提供任何其他代码,因此我使用了 vanilla 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>


推荐阅读