Html option with images

Как добавить изображения в список выбора?

Я хочу использовать изображение в раскрывающемся списке как drop-down-icon.jpeg. Я хочу добавить кнопку вместо выпадающего значка. Как это сделать?

как общее решение: если вы можете, соберите ваши значки в виде SVG, импортируйте их в выбранный вами шрифт в личный диапазон Unicode, используйте этот шрифт в ваших

8 ответов

В Firefox вы можете просто добавить фоновое изображение к опции:

Еще лучше, вы можете отделить HTML и CSS как

select#gender option[value="male"] < background-image:url(male.png); >select#gender option[value="female"] < background-image:url(female.png); >select#gender option[value="others"]

В других браузерах единственный способ сделать это — использовать некоторую библиотеку виджетов JS, например, jQuery UI, например используя Selectable.

Из jQuery UI 1.11 доступен Selectmenu, который очень близок к тому, что вы хотите.

@IvanKuckir — Пфффф. W3C все еще «обсуждает» причины, почему и почему этого не следует делать, и после проведения исследования по этой теме, комитет затем обсудит потенциальные преимущества и недостатки, позволяющие это сделать. После этого будет проведено практическое исследование обратной совместимости. Затем они проведут исследование для дальтоников. Как только рекомендация будет сделана, будет проведено исследование о потенциальных побочных эффектах на другие элементы (такие как флажок). После всего этого у них будет исследование, чтобы решить, если все эти исследования, где это необходимо.

Вы можете использовать iconselect.js; Значок/выбор изображения (выпадающее меню, выпадающее меню)

Изображение 110497

 var iconSelect; window.onload = function()< iconSelect = new IconSelect("my-icon-select"); var icons = []; icons.push(); icons.push(); icons.push(); iconSelect.refresh(icons); >; 

Этот плагин имеет самое странное «требование», которое я когда-либо видел; CSS и функция прокрутки не работают, если у вас определен .

Мое решение — использовать FontAwesome, а затем добавить библиотечные образы в текст! Вам просто нужны Юникоды, и они найдены здесь: FontAwesome Reference File forUnicodes

Вот пример фильтра состояния:

  

Обратите внимание, что семейство шрифтов: Arial, FontAwesome; требуется назначить в стиле для выбора, как указано в примере!

Это именно то, что я пытался сделать! Я действительно не хотел реализовывать другой плагин js — так что это прекрасно, так как я уже использую значки FontAwesome на своем веб-сайте.

это решение не работает с этой опцией, только когда выбрано (ручка: codepen.io/wtfgraciano/pen/YMwWqK )

Что вы имеете в виду добавить библиотечные изображения в виде текста? Извините, я не совсем понимаю, вы не против объяснить?

@RyanN1220 RyanN1220 Fontawesome — это библиотека с мини-изображениями. И каждое изображение имеет соответствующий текст Unicode, который вы можете применить. Смотрите ссылку в ответе для текстового кода. ( fontawesome.com/cheatsheet?from=io#social-buttons ) Ничего особенного, просто следуйте примеру в ответе, и вам будет хорошо идти.

Читайте также:  Django python for mac

Еще одно решение для перекрестного браузера jQuery для этой проблемы — http://designwithpc.com/Plugins/ddSlick, которое сделано именно для этого использования.

@RousseauAlexandre проверяя консоль на этом другом сайте, я вижу 403 ошибки для содержания автора. Я отправил ему сообщение об этом, так как жалобы здесь не принесут пользы.

вы правы, я получил ошибку my.hellobar.com/45874_63207.js not found, а затем TypeError: $(. ).ddslick не является функцией в консоли Firefox

Просто ссылка на библиотеку не является хорошим ответом. Ссылки на него, объяснение, почему это решает проблему, и предоставление кода с использованием библиотеки для этого — лучший ответ. Смотрите: Как я могу сделать ссылку на внешний ресурс в сообществе?

У вас уже есть несколько ответов, которые предлагают использовать JavaScript/jQuery. Я собираюсь добавить альтернативу, которая использует только HTML и CSS без каких-либо JS.

Основная идея состоит в том, чтобы использовать набор переключателей и меток (которые активируют/деактивируют переключатели), а с помощью CSS-управления будет отображаться только метка, связанная с выбранным переключателем. Если вы хотите разрешить выбор нескольких значений, вы можете достичь этого, используя флажки вместо переключателей.

Вот пример. Код может быть немного беспорядочным (особенно по сравнению с другими решениями):

.select-sim < width:200px; height:22px; line-height:22px; vertical-align:middle; position:relative; background:white; border:1px solid #ccc; overflow:hidden; >.select-sim::after < content:"▼"; font-size:0.5em; font-family:arial; position:absolute; top:50%; right:5px; transform:translate(0, -50%); >.select-sim:hover::after < content:""; >.select-sim:hover < overflow:visible; >.select-sim:hover .options .option label < display:inline-block; >.select-sim:hover .options < background:white; border:1px solid #ccc; position:absolute; top:-1px; left:-1px; width:100%; height:88px; overflow-y:scroll; >.select-sim .options .option < overflow:hidden; >.select-sim:hover .options .option < height:22px; overflow:hidden; >.select-sim .options .option img < vertical-align:middle; >.select-sim .options .option label < display:none; >.select-sim .options .option input < width:0; height:0; overflow:hidden; margin:0; padding:0; float:left; display:inline-block; /* fix specific for Firefox */ position: absolute; left: -10000px; >.select-sim .options .option input:checked + label < display:block; width:100%; >.select-sim:hover .options .option input + label < display:block; >.select-sim:hover .options .option input:checked + label
 

Источник

Putting Images With Options in a Dropdown List

In Firefox you can just add background image to option:

Better yet, you can separate HTML and CSS like that

select#gender option[value=»male»] < background-image:url(male.png); >
select#gender option[value=»female»] < background-image:url(female.png); >
select#gender option[value=»others»]

In other browsers the only way of doing that would be using some JS widget library, like for example jQuery UI, e.g. using Selectable.

From jQuery UI 1.11, Selectmenu widget is available, which is very close to what you want.

want to show image/icons in dropdown list

Check this example .. everything has been done easily http://jsfiddle.net/GHzfD/

EDIT: Updated/working as of 2013, July 02: jsfiddle.net/GHzfD/357

#webmenu width:340px;
>









$("body select").msDropDown();

Hack for adding images in ‘select’ list of html

Check the snippet below. I created a custom component using UL>LI.

var placeholder = document.getElementById('placeholder');
var dropdown = document.getElementById('custom-select');

placeholder.addEventListener('click', function() if(dropdown.classList.contains('active')) dropdown.classList.remove('active')
> else dropdown.classList.add('active')
>
>)
.custom-select .dropdown list-style: none; 
padding: 0;
display: none;
>

.dropdown .img-wrapper,
.placeholder .img-wrapper display: inline-block;
max-width: 30px;
>

.dropdown img,
.placeholder img max-width: 100%;
>

.placeholder display: flex;
align-items: center;
padding: 10px;
cursor: pointer;
position: relative;
>

.placeholder::before,
.placeholder::after content: "";
display: inline-block;
height: 2px;
width: 10px;
background-color: #aaa;
position: absolute;
right: 0;
>

.placeholder::before transform: rotate(45deg);
right: 20px;
>

.placeholder::after transform: rotate(-45deg);
right: 15px;
>

.custom-select.active .placeholder::after right: 20px;
>

.custom-select.active .placeholder::before right: 15px;
>

.custom-select.active .dropdown display: flex;
flex-direction: column;
box-shadow: 1px 1px 6px 1px #ddd;
position: absolute;
top: 40px;
right: 0;
left: 0;
min-width: 200px;
>

.dropdown li display: flex;
align-items: center;
background-color: #fff;
padding: 10px;
transition: all 0.3s ease;
cursor: pointer;
>

.dropdown li:not(:last-child) border-bottom: 1px solid #aaa;
>

.dropdown li:hover box-shadow: 0px 0px 11px 1px rgba(182, 182, 182, 0.75) inset;
>

.custom-select display: inline-flex;
flex-direction: column;
position: relative;
width: 100px;
>
input border: 0;
outline: none;
box-shadow: none;
width: 40px;
display: inline-block;
height: 30px;
text-align: right;
>

.wrapper display: inline-flex;
position: relative;
border: 1px solid #ddd;
border-radius: 5px;
margin-top: 50px;
align-items: center;
>

.input-label position: absolute;
background-color: #fff;
top: -6px;
display: inline-block;
left: 10px;
padding: 0 5px;
color: #aaa;
>
 






BTC




Bitcoin (BTC)



Ethereum (ETH)



Cardano (ADA)

How to add small thumbnails to `option` elements in a `select` list?

Despite the other answers here, you won’t be able to do this reliably in all browsers. Each browser presents a field completely differently. Your best bet is to fake a select field using normal HTML elements, and when it changes, update a hidden select field with javascript.

See this SO answer
putting images with options in a dropdown list

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow adding icons/images to and s #3596

Allow adding icons/images to and s #3596

addition/proposal New features or enhancements needs implementer interest Moving the issue forward requires implementers to express interest topic: forms

Comments

Very often, it is necessary to include icons or images with a list of options. I prefer to use native controls for a variety of reasons, including accessibility, mobile form flow, the fact that boxes can extend outside of their frame or window while being positioned according to the user’s OS’s rules, etc. However, some options presented to users may that of an icon or a color, where naming the option simply does not communicate the value quite like an image would. In such a case, developers are often forced to use custom form elements which have accessibility and other issues. One possible workaround is to use radio buttons, but when you have perhaps 20 or 30 choices, that can be rather unwieldy. Native OS menus have support for icons, and while the element is essentially a replaced element by a native OS menu, it definitely is a very limited version of it. I will attach some screenshots to illustrate some use cases from an app I recently built.

  1. A limited selection of colors. In such a case, simply listing the words is not sufficient, as shades of said colors are important to the user. screen shot 2018-03-27 at 10 26 56 pm
  2. A selection of icons. Here it’s even more important to have illustrations, as people may imagine a variety of icons for any particular word. Seeing said icon is important in making the decision. screen shot 2018-03-27 at 10 27 18 pm
  3. Displaying logos of brands/companies/organizations. This is of course more of a nice to have, since the names of said brands already evoke an image in users’ minds, but it comes free with implementing this feature.

I’ve wanted to propose this feature for a while now, as @wycats suggested I do on Twitter, but I’m only getting around to it now. Here’s the thread where it was mentioned: https://twitter.com/wycats/status/945714039631446016

As for possible solutions, perhaps adding an icon attribute to the element or allowing an , , etc. inside might work. A somewhat less desirable, but still usable solution might be to allow styling elements as suggested in w3c/csswg-drafts#2013 and use ::before pseudo-elements to inject said icons. I would prefer a way where the OS would be able to render the icons at a consistent size and — for icons that don’t need to use colors — color, as they are rendered in native OS menus, but I’m getting ahead of myself.

The text was updated successfully, but these errors were encountered:

Источник

HTML Select item with Icons in addition to just text labels – applying the CSS background-style to the HTML OPTION element

We have been using JIRA for our Incident Management the last six
months or so, and one of the UI features in JIRA that suddenly struck
me as being somewhat odd and primarily quite cool at the same time, was
the Issue Type select-item that not only contained text-labels, as HTML
Select items usually do, but also had icons in them:

For
me this was a more or less new HTML feature, and one that I would like
to use myself sometime. So I took a look at the HTML source and – of
course – it turned out to be a CSS trick, using the background-image
style on the OPTION elements in the SELECT. I would never had thought
that this CSS style could also be applied to OPTIONs, so once again it
is proved that you should try out everything, including things you know not to be possible. The HTML source from this JIRA item looked as follows:

 

The next step of course is actually using this feature myself in my
own applications and then making the icons dynamic along with the data;
typically the content of a SELECT item will be produced by some backing
bean or other dynamic data source and that bean or that source should
now provide an icon reference in addition to label and value. And it
would be nice to have a JSF component – an extension of UISelectMany or
UISelectOne – that can render the background icon too. The real
challenge is finding some time for this, obviously.

Источник

Оцените статью