Как убрать файл не выбран html
Перейти к содержимому

Как убрать файл не выбран html

  • автор:

Как у input type file убрать кнопку, но показывать название файла который выбрали

Частая задача — красиво оформить поле для прикрепления файла.

Основной проблемой тут является то, что сам элемент input type=»file» через CSS кастомизировать можно плохо, поэтому его просто скрывают и оформляют кнопку место его кнопку, ссылку, label.

Но и тут есть проблема, обычно, такие кнопки не отображают файл который был выбран пользователем и, иногда, посетители сайта не могут понять, прикрепился их файл или нет.

Для реяние этой проблемы подойдет небольшой JS скрипт:

$(document).ready( function() < $('#bntUpload').click(function()< $("#so_file").click(); >); $('#so_file').change(function() < $('#selected_filename').text($('#so_file')[0].files[0].name); >); >);

Как у input type=»file» убрать надпись «Выберите файл»?

Возможно ли это сделать без label?

Лучший ответ

Можно полностью избавиться от кнопки через display: none, примененного к селектору input file. Сам текст напрямую редактировать нельзя даже через JS, к нему просто нет доступа.

.file::file-selector-button < 
display: none;
>

Если кнопку необходимо оставить, как вариант, можно покрасить текст в прозрачный rgba(). кнопка останется, текста не будет.

.file::file-selector-button < 
color: rgba(0,0,0,0);
>

Остальные ответы
https://habr.com/ru/post/321250/
здесь гляньте, интересно
Давид МейстерМастер (1456) 7 месяцев назад
Ну так это способ через label
Илья АганичевМудрец (13087) 7 месяцев назад
А что Вы хотите? Вводить имя файла? Тогда тип на text смените

Давид Мейстер Мастер (1456) Илья Аганичев, Я просто указал в вопросе «Возможно ли это сделать без label?» вы видимо не заметили

Нестандартные поля выбора файла

Кроссбраузерно оформить поле выбора файла ().

По умолчанию поля выбора файла в разных браузерах выглядят по разному:

input type=file в firefox в Firefox 2.0
input type=file в IE6 в IE6
input type=file в Opera в Opera 9.01
input type=file в Chrome и Safari в Chrome и Safari

input type=file по дизайну

А по дизайну, к примеру, нужно сделать поле оформить так:

Решение

Для решения задачи делаем следующее:

  • делаем поле input type=»file» полностью прозрачным, чтобы скрыть оформление по умолчанию, при этом оставив работоспособным
  • подкладываем блок с фоновой картинкой оформления поля
  • т.к. поле с выбором файла у нас полностью прозрачное, чтобы пользователь увидел, чтоб файл успешно выбран, добавляем обычной текстовое поле поверх оформления и при выборе нового файла, с помощью javascript название присваиваем значению текстового поля
.type_file < /* блок-родитель, внутри которого будут позиционироваться остальные элементы для реализации стильного поля выбора файлов */ position: relative; height: 26px; >.inputFile < /* поле type="file" */ position: absolute; /* абсолютное позиционирование, чтобы можно было совместить поле и блок с оформлением */ top: 0; left: 0; z-index: 2; /* z-слой должен быть больше, чем у блока с оформлением */ filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0); /* делаем поле абсолютно прозрачным */ -moz-opacity: 0; -khtml-opacity: 0; opacity: 0; width: 267px; /* задаем ширину для всех браузеров. Для firefox подбираем значение параметра size в поле */ >.fonTypeFile < /* блок с оформлением */ width: 267px; /* размеры картинки для оформления */ height: 26px; background: url(images/inputFile.png); /* картинка оформления поля */ position: absolute; top: 0; left: 0; z-index: 1; /* z-слой меньше, чем у поля выбора файла */ >.inputFileVal < /* поле, в котором будет показан результат выбора файла */ position: absolute; top: 3px; left: 5px; z-index: 2; width: 175px; background: none; border: none; >

Недостатки

  • CSS-код не валиден (можно обойти, если воспользоваться условными комментариями для IE6 и закрыть глаза на некоторые старые браузеры, убрав -moz-opacity и -khtml-opacity)
  • требуется javascript
  • размер кнопки выбора файла по дизайну должен примерно совпадать с размера кнопки у обычного

Кнопка выбора файла любого размера

update: Егор Скорняков

Например имеем задачу реализовать кнопку выбора файлов вот такого размера:

Нестандартная кнопка выбора файла

Как уже отмечено, вышеприведенный способ накладывает ограничения на размер кнопки. Но что же делать, если хочется сделать огромную кнопку выбора файлов? Кроссбраузерной кликабельной частью поля выбора файла является кнопка «Browse» или «Обзор» (в Safari и Chrome кликабельной частью является вся площадь нашего поля ), сделовательно нашей задачей будет сделать эту область большого размера.

С помошью свойства height:100%; мы можем задать большую высоту, но, к сожалению, на ширину кнопки мы повлиять не можем. Для этого нам на помошь приходит небольшая хитрость: прописываем для нашего поля например font-size: 200px; (что заставит кнопку стать больше).

Далее создаём контейнер, который будет иметь в фоне изображение нашей кнопки и обязательно контейнеру прописываем overflow: hidden; для того что бы он обрезал лишнее, внутри него абсолютно позиционируем наше поле относительно правого верхнего угла, и скрываем его с помошью прозрачности равной «0».

.button < width: 80px; /* размеры кноки */ height: 42px; background: url(path-to/upload-photo.png); overflow: hidden; /* поможет избежать выхода поля за границы кнопки */ position: relative; /* относительно этого блока будем позиционировать поле */ >.button input < height: 200px; position: absolute; /* для более простого позиционирования поля */ top: 0; /* начальные координаты */ right: 0; opacity: 0; /* само поле делаем прозрачным, чтобы показать фон кнопки */ filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0); cursor: pointer; font-size: 200px; >

Тут вы можете Посмотреть результат.Проверено в:

Заметки

Кроссбраузерный нужный вид указателя мыши на кнопке пока не получилось добиться.

  • CSS приемы
    • «Дергание» сайта
    • background position со смещением
    • clearfix
    • CSS прозрачность
    • CSS хаки
    • RGBA — CSS полупрозрачность
    • Затемнение фона
    • Кроссбраузерный

    • Обнуление отступов
    • Порядок описания ссылок
    • Прелоад изображений
    • Сброс стилей
    • Сокращения в CSS
    • Убираем рамку с эл-ов в фокусе
    • Условные CSS
    • Условные комментарии
    • Поворот вокруг своей оси
    • Поворот объекта вокруг свой
    • Resize для textarea в Safari и Chrome
    • Блочная верстка форм
    • Кастомные checkbox и radio на CSS
    • Кросбраузерные input и textarea
    • Кроссбраузерный button
    • Нестандартные checkbox
    • Нестандартные radio
    • Нестандартные select
    • Нестандартные select multiple
    • Нестандартные поля выбора файла
    • Нестандартные текстовые поля
    • О кроссбраузерности placeholder
    • Отступы у checkbox и radio
    • Оформление input type=search
    • Резиновая кнопка
    • Текст в поле type=»password»
    • Блоки равной высоты в строке
    • Колонки равной высоты
    • Прижимаем подвал к низу
    • Ресайз окна: потомок перерос родителя
    • Сайт в центре экрана
    • Фиксированная колонка + резиновая + clear:both
    • CSS 3D лента
    • CSS3 всплывающие подсказки
    • IMG внутри блока — убираем странный отступ
    • IMG: меняем рисунок при наведении
    • Аккордеон на чистом CSS3
    • Валидный target=»_blank»
    • Верстка рейтингов
    • Верстка содержания
    • Вставка спецсимволов в генерируемый контент
    • Вставка стрелок
    • Индивидуальные стили для li. Избавляемся от классов.
    • Масштабируемая картинка в резиновой колонке
    • Многоколоночный текст на CSS3
    • Нестандартное подчеркивание
    • Отменяем обтекание текстом картинки
    • Оформление внешних ссылок
    • Оформление изображений по align
    • Оформляем «ol»
    • Правильные анонсы новостей
    • Список определений. Требуем невозможного.
    • Firefox
      • -moz-box-shadow и -moz-border-radius — это кошмар CPU
      • Позиционирование внутри button
      • Ширина input type=file
      • Onload в IE9
      • z-index в IE6-7
      • Баг с текстом при применении Alpha фильтра
      • Масштабирование и PIE
      • Отступы в кнопках в IE6-7
      • Проблемы с em
      • Эмуляция after и before для IE 6-7
      • Эмуляция data:URL для IE6-7 — используем MHTML-включение
      • hasLayout
      • Max-width
      • Min-height
      • Min-width
      • Min-width и max-width одновременно
      • PNG и прозрачность
      • Высота блока 1px
      • Дублирование символов
      • Дырка под футером
      • Как перекрыть select
      • Обрезка контента c отрицательным margin в IE6
      • Отступы плавающих блоков
      • Проблемы с размерами блоков
      • Псевдокласс :first-child
      • Псевдокласс hover в IE 6
      • Селектор потомков >
      • Селекторы атрибутов [type=…]
      • Сестринский селектор
      • Смещение на 1px
      • Ссылки с вложением
      • Устраняем flickering
      • Эмуляция position:fixed
      • overflow-y
      • Не подгружаются шрифты @font-face
      • Проблема с oveflow: hidden
      • Скругление img
      • HTML шаблон для мобильных устройств
      • Выпадающее меню на CSS
      • Выравнивание навигации из блоков по центру
      • Выравнивание навигации по середине
      • Резиновое меню
      • Резиновое меню из блоков
      • Убираем класс для первого элемента
      • Box-sizing: переключаем блочную модель
      • inline-block: простое свойство для непростых задач
      • Вертикальная позиция для строчного элемента
      • Вертикальное выравнивание
      • Выравнивание по центру с position: absolute
      • Вычисляемые отступы
      • Два в одном: позиция + размеры
      • Долой отступы между строчными элементами (и блоками)
      • Обходим схлопывание margin
      • Центрирование картинки в блоке
      • Центрирование резинового блока по горизонтали
      • Активация flash
      • Вставка flash в HTML
      • Вставляем ролик с YouTube
      • Как отключить flash
      • Как перекрыть flash
      • Параметры для вставки объектов
      • Ссылка на flash объекте
      • CSS треугольники
      • Аппаратное ускорение анимации
      • Встраиваем изображения — data:URL
      • Градиент: CSS3 против CSS2 + картинка
      • Лесенка спрайтов — сложный случай поклейки
      • На одну картинку меньше. Спецсимвол ×
      • Необычные тени с CSS3 box-shadow
      • Оптимизация Google Web Fonts
      • Оптимизация фонов с помощью Canvas
      • Проблемы с border-radius
      • Псевдоэлемент before для маркера списка
      • Скругление углов. Обзор методов.
      • Сокращаем HTML5 код
      • Спрайты: меньше картинок — больше скорость
      • Тень для блока
      • Фигуры с углами на CSS
      • Шаблоны градиентов
      • Дополнение Skype
      • Подключить favicon
      • Профилактика сайта: максимально простое оповещение
      • Ссылки на skype
      • @font-face в деталях
      • Cufon — нестандартный шрифт средствами JS
      • font-size: 100.01% для html
      • Безопасные шрифтовые CSS стеки для англоязычных текстов
      • Безопасные шрифтовые CSS стеки для рунета
      • Безопасные шрифты
      • Вертикальный текст
      • Используем псевдоэлемент :first-letter
      • Контур для текста
      • Нестандарный шрифт. Быть ему или нет?
      • Нестандартный шрифт средствами CSS
      • Плавающий :first-letter
      • Подмена текста изображением
      • Соответствия шрифтов Windows, Mac и Unix/Linux
      • Строчный :first-letter
      • Текст под углом
      • Текст с CSS градиентом
      • Тень для текста
      • Эффект отражения

      Как убрать файл не выбран html

      Атрибут value элемента input содержит DOMString , который представляет путь к выбранным файлам. Если пользователь выбрал несколько файлов, value представляет первый файл из списка. Остальные файлы можно определить используя HTMLInputElement.files (en-US) свойство элемента input.

      **Примечание:**1. Если выбрано несколько файлов, строка представляет собой первый выбранный файл. JavaScript предоставляет доступ к остальным файлам через свойство FileList . 2. Если не выбрано ни одного файла, .строка равна «» (пустая). 3. Строка начинается с C:\fakepath\ , для предотвращения определения файловой структуры пользователя вредоносным ПО.

      Additional attributes

      In addition to the common attributes shared by all elements, inputs of type file also support:

      A FileList object that lists every selected file. This list has no more than one member unless the multiple attribute is specified.

      Using file inputs

      A basic example

      form method="post" enctype="multipart/form-data"> div> label for="file">Choose file to uploadlabel> input type="file" id="file" name="file" multiple /> div> div> button>Submitbutton> div> form> 
      div  margin-bottom: 10px; > 

      This produces the following output:

      Примечание: You can find this example on GitHub too — see the source code, and also see it running live.

      Regardless of the user’s device or operating system, the file input provides a button that opens up a file picker dialog that allows the user to choose a file.

      Including the multiple attribute, as shown above, specifies that multiple files can be chosen at once. The user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down Shift or Control , and then clicking). If you only want the user to choose a single file per , omit the multiple attribute.

      When the form is submitted, each selected file’s name will be added to URL parameters in the following fashion: ?file=file1.txt&file=file2.txt

      Getting information on selected files

      The selected files’ are returned by the element’s files property, which is a FileList object containing a list of File objects. The FileList behaves like an array, so you can check its length property to get the number of selected files.

      Each File object contains the following information:

      A number specifying the date and time at which the file was last modified, in milliseconds since the UNIX epoch (January 1, 1970 at midnight).

      A Date object representing the date and time at which the file was last modified. This is deprecated and should not be used. Use lastModified instead.

      The size of the file in bytes.

      A string specifying the file’s path relative to the base directory selected in a directory picker (that is, a file picker in which the webkitdirectory attribute is set). This is non-standard and should be used with caution.

      Примечание: You can set as well as get the value of HTMLInputElement.files in all modern browsers; this was most recently added to Firefox, in version 57 (see баг 1384030).

      Limiting accepted file types

      Often you won’t want the user to be able to pick any arbitrary type of file; instead, you often want them to select files of a specific type or types. For example, if your file input lets users upload a profile picture, you probably want them to select web-compatible image formats, such as JPEG or PNG (en-US) .

      Acceptable file types can be specified with the accept attribute, which takes a comma-separated list of allowed file extensions or MIME types. Some examples:

      • accept=»image/png» or accept=».png» — Accepts PNG files.
      • accept=»image/png, image/jpeg» or accept=».png, .jpg, .jpeg» — Accept PNG or JPEG files.
      • accept=»image/*» — Accept any file with an image/* MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.)
      • accept=».doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document» — accept anything that smells like an MS Word document.

      Let’s look like a more complete example:

      form method="post" enctype="multipart/form-data"> div> label for="profile_pic">Choose file to uploadlabel> input type="file" id="profile_pic" name="profile_pic" accept=".jpg, .jpeg, .png" /> div> div> button>Submitbutton> div> form> 
      div  margin-bottom: 10px; > 

      This produces a similar-looking output to the previous example:

      Примечание: You can find this example on GitHub too — see the source code, and also see it running live.

      It may look similar, but if you try selecting a file with this input, you’ll see that the file picker only lets you select the file types specified in the accept value (the exact nature differs across browsers and operating systems).

      Screenshot of a macOS file picker dialog. Files other than JPEG are grayed-out and unselectable.

      The accept attribute doesn’t validate the types of the selected files; it simply provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types.

      Because of this, you should make sure that the accept attribute is backed up by appropriate server-side validation.

      Examples

      In this example, we’ll present a slightly more advanced file chooser that takes advantage of the file information available in the HTMLInputElement.files (en-US) property, as well as showing off a few clever tricks.

      Примечание: You can see the complete source code for this example on GitHub — file-example.html (see it live also). We won’t explain the CSS; the JavaScript is the main focus.

      First of all, let’s look at the HTML:

      form method="post" enctype="multipart/form-data"> div> label for="image_uploads">Choose images to upload (PNG, JPG)label> input type="file" id="image_uploads" name="image_uploads" accept=".jpg, .jpeg, .png" multiple /> div> div class="preview"> p>No files currently selected for uploadp> div> div> button>Submitbutton> div> form> 
      html  font-family: sans-serif; > form  width: 600px; background: #ccc; margin: 0 auto; padding: 20px; border: 1px solid black; > form ol  padding-left: 0; > form li, div > p  background: #eee; display: flex; justify-content: space-between; margin-bottom: 10px; list-style-type: none; border: 1px solid black; > form img  height: 64px; order: 1; > form p  line-height: 32px; padding-left: 10px; > form label, form button  background-color: #7f9ccb; padding: 5px 10px; border-radius: 5px; border: 1px ridge black; font-size: 0.8rem; height: auto; > form label:hover, form button:hover  background-color: #2d5ba3; color: white; > form label:active, form button:active  background-color: #0d3f8f; color: white; > 

      This is similar to what we’ve seen before — nothing special to comment on.

      Next, let’s walk through the JavaScript.

      var input = document.querySelector("input"); var preview = document.querySelector(".preview"); input.style.opacity = 0; 

      Примечание: opacity is used to hide the file input instead of visibility: hidden or display: none , because assistive technology interprets the latter two styles to mean the file input isn’t interactive.

      Next, we add an event listener to the input to listen for changes to its selected value changes (in this case, when files are selected). The event listener invokes our custom updateImageDisplay() function.

      .addEventListener("change", updateImageDisplay); 

      Whenever the updateImageDisplay() function is invoked, we:

      • Use a while loop to empty the previous contents of the preview .
      • Grab the FileList object that contains the information on all the selected files, and store it in a variable called curFiles .
      • Check to see if no files were selected, by checking if curFiles.length is equal to 0. If so, print a message into the preview stating that no files have been selected.
      • If files have been selected, we loop through each one, printing information about it into the preview . Things to note here:
      • We use the custom validFileType() function to check whether the file is of the correct type (e.g. the image types specified in the accept attribute).
      • If it is, we:
        • Print out its name and file size into a list item inside the previous (obtained from curFiles[i].name and curFiles[i].size ). The custom returnFileSize() function returns a nicely-formatted version of the size in bytes/KB/MB (by default the browser reports the size in absolute bytes).
        • Generate a thumbnail preview of the image by calling window.URL.createObjectURL(curFiles[i]) and reducing the image size in the CSS, then insert that image into the list item too.
        function updateImageDisplay()  while (preview.firstChild)  preview.removeChild(preview.firstChild); > var curFiles = input.files; if (curFiles.length === 0)  var para = document.createElement("p"); para.textContent = "No files currently selected for upload"; preview.appendChild(para); > else  var list = document.createElement("ol"); preview.appendChild(list); for (var i = 0; i  curFiles.length; i++)  var listItem = document.createElement("li"); var para = document.createElement("p"); if (validFileType(curFiles[i]))  para.textContent = "File name " + curFiles[i].name + ", file size " + returnFileSize(curFiles[i].size) + "."; var image = document.createElement("img"); image.src = window.URL.createObjectURL(curFiles[i]); listItem.appendChild(image); listItem.appendChild(para); > else  para.textContent = "File name " + curFiles[i].name + ": Not a valid file type. Update your selection."; listItem.appendChild(para); > list.appendChild(listItem); > > > 

        The custom validFileType() function takes a File object as a parameter, then loops through the list of allowed file types, checking if any matches the file’s type property. If a match is found, the function returns true . If no match is found, it returns false .

        var fileTypes = ["image/jpeg", "image/pjpeg", "image/png"]; function validFileType(file)  for (var i = 0; i  fileTypes.length; i++)  if (file.type === fileTypes[i])  return true; > > return false; > 

        The returnFileSize() function takes a number (of bytes, taken from the current file’s size property), and turns it into a nicely formatted size in bytes/KB/MB.

        function returnFileSize(number)  if (number  1024)  return number + "bytes"; > else if (number > 1024 && number  1048576)  return (number / 1024).toFixed(1) + "KB"; > else if (number > 1048576)  return (number / 1048576).toFixed(1) + "MB"; > > 

        The example looks like this; have a play:

        Specifications

        Specification
        HTML Standard
        # file-upload-state-(type=file)

        Browser compatibility

        BCD tables only load in the browser

        See also

        • Using files from web applications — contains a number of other useful examples related to and the File API.

        Found a content problem with this page?

        • Edit the page on GitHub.
        • Report the content issue.
        • View the source on GitHub.

        This page was last modified on 11 окт. 2023 г. by MDN contributors.

        Your blueprint for a better internet.

        MDN

        Support

        • Product help
        • Report an issue

        Our communities

        Developers

        • Web Technologies
        • Learn Web Development
        • MDN Plus
        • Hacks Blog
        • Website Privacy Notice
        • Cookies
        • Legal
        • Community Participation Guidelines

        Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
        Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *