В JavaScript я могу сделать огонь события “щелчка” программно для входного элемента файла?

Нет. Вы создали разреженный массив

. Вместо этого используйте объект, тогда Object.keys(obj) вернет количество записей

var obj = {}

obj[1] = "test";

console.log(
  Object.keys(obj).length // shows the number of elements
)

254
задан user28655 16 October 2008 в 13:56
поделиться

3 ответа

Я весь день искал решение. И вот какие выводы я сделал:

  1. По соображениям безопасности Opera и Firefox не позволяют запускать ввод файла.
  2. Единственная удобная альтернатива - создать «скрытый» ввод файла (используя непрозрачность, а не «скрытый» или «отображение: нет»!), А затем создать кнопку «под ним». Таким образом, кнопка видна, но при нажатии пользователем она фактически активирует ввод файла.

Надеюсь, это поможет! :)

<div style="display: block; width: 100px; height: 20px; overflow: hidden;">
<button style="width: 110px; height: 30px; position: relative; top: -5px; left: -5px;"><a href="javascript: void(0)">Upload File</a></button>
<input type="file" id="upload_input" name="upload" style="font-size: 50px; width: 120px; opacity: 0; filter:alpha(opacity=0);  position: relative; top: -40px;; left: -20px" />
</div>
257
ответ дан 23 November 2019 в 02:48
поделиться

I was researching this a while ago because I wanted to create a custom button that would open the file dialog and start the upload immediately. I just noticed something that might make this possible - firefox seems to open the dialog when you click anywhere on the upload. So the following might do it:

  1. Create a file upload and a separate element containing an image that you want to use as the button
  2. Arrange them to overlap and make the file element backgroud and border transparent so the button is the only thing visible
  3. Add the javascript to make IE open the dialog when the button/file input is clicked
  4. Use an onchange event to submit the form when a file is selected

This is only theoretical since I already used another method to solve the problem but it just might work.

2
ответ дан 23 November 2019 в 02:48
поделиться

Для тех, кто понимает, что надо накладывать невидимую форму поверх ссылки, но лень писать, я написал для вас. Что ж, для меня, но с таким же успехом можно поделиться. Комментарии приветствуются.

HTML (Где-то):

<a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a>

HTML (Где-то вас не волнует):

<div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;">
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="file" />
    </form>
</div>

JavaScript:

function pageY(el) {
    var ot = 0;
    while (el && el.offsetParent != el) {
        ot += el.offsetTop ? el.offsetTop : 0;
        el = el.offsetParent;
    }
    return ot;
}

function pageX(el) {
    var ol = 0;
    while (el && el.offsetParent != el) {
        ol += el.offsetLeft ? el.offsetLeft : 0;
        el = el.offsetParent;
    }
    return ol;
}

function fileMove() {
    if (navigator.appName == "Microsoft Internet Explorer") {
        return; // Don't need to do this in IE. 
    }
    var link = document.getElementById("fileLink");
    var form = document.getElementById("uploadForm");
    var x = pageX(link);
    var y = pageY(link);
    form.style.position = 'absolute';
    form.style.left = x + 'px';
    form.style.top = y + 'px';
}

function fileBrowse() {
    // This works in IE only. Doesn't do jack in FF. :( 
    var browseField = document.getElementById("uploadForm").file;
    browseField.click();
}
10
ответ дан 23 November 2019 в 02:48
поделиться
Другие вопросы по тегам:

Похожие вопросы: