我想在选择选项中显示每个国家的国旗。
这是我试过的代码:
<select id="slcCountry">
<option flag="https://restcountries.eu/data/afg.svg">AFG</option>
<option flag="https://restcountries.eu/data/ala.svg">ALA</option>
<option flag="https://restcountries.eu/data/alb.svg">ALB</option>
</select>
这是显示图片的css
select option {
background-image: url(attr(flag));
background-repeat: no-repeat;
background-size: 30px;
background-position: 10px 6px;
width: 32px;
height: 34px;
}
我如何在此处显示列表的每个图像(标志)。请帮助我。
最佳答案
首先,自定义属性使用 html5 data attribute而不是标志属性(无效的 html,),
用简单的选择来实现这一点并不容易或不可能,所以使用插件和一些 css/js 技巧是可能的,
我用过 bootstrap select ,使用 bootstrap 3 和 jquery,结果如下:
请看下面的片段:
$(function() {
$('.selectpicker').selectpicker({
size: 4
});
// selector for generated dropdonw button
var $button = $("button[data-id='slcCountry']");
//generate img for each selectpicker option
$("#slcCountry option").each(function(i, el) {
var flag = $(el).data("flag");
if (flag)
$button.next().find("li[data-original-index=" + i + "] a").css("background-image", "url(" + flag + ")");
});
//cahnge event to assign icon to selected elmen t
$("#slcCountry").on("change", function(e) {
var flag = $("#slcCountry option:selected").data("flag");
if (flag)
$button.find(".filter-option").css("background-image", "url(" + flag + ")");
else
$button.find(".filter-option").css("background-image", "url('')")
});
$('.selectpicker').trigger('change');
});
#img {
width: 200px;
height: 150px;
}
.dropdown-menu ul li a,
button[data-id='slcCountry'] .filter-option {
background-size: 25px;
background-position-y: center;
background-repeat: no-repeat;
background-position-x: 95%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<select class="selectpicker" id="slcCountry">
<option data-flag="https://restcountries.eu/data/afg.svg">AFG</option>
<option data-flag="https://restcountries.eu/data/dza.svg">DZA</option>
<option data-flag="https://restcountries.eu/data/alb.svg">ALB</option>
</select>
关于jquery - 在 HTML 选择元素中使用 attr 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49667549/