0. 安装/引入 与使用
点击这里进入官方页,查看引入方法与基本使用.
1. 正事儿
项目需要,要在某页面的select项中加入品牌logo图片,其他页面中的选择框都使用的Bootstrap-select插件,查看源码后发现它只支持在<option/>标签中添加 'data-icon' 属性(下面代码中的icon变量):
var optionClass = this.className || '',
inline = htmlEscape(this.style.cssText),
text = $this.data('content') ? $this.data('content') : $this.html(),
tokens = $this.data('tokens') ? $this.data('tokens') : null,
subtext = typeof $this.data('subtext') !== 'undefined' ? '<small class="text-muted">' + $this.data('subtext') + '</small>' : '',
icon = typeof $this.data('icon') !== 'undefined' ? '<span class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></span> ' : '',
$parent = $this.parent(),
isOptgroup = $parent[0].tagName === 'OPTGROUP',
isOptgroupDisabled = isOptgroup && $parent[0].disabled,
isDisabled = this.disabled || isOptgroupDisabled,
prevHiddenIndex;
然后在后面的代码中拼接html:
if (icon !== '' && isDisabled) {
icon = '<span>' + icon + '</span>';
}
if (!$this.data('content')) {
// Prepend any icon and append any subtext to the main text.
text = icon + img + '<span class="text">' + text + subtext + '</span>';
}
要添加图片功能,于是添加一个 img变量用于拼接<img>标签,并拼接进text中:
var optionClass = this.className || '',
inline = htmlEscape(this.style.cssText),
text = $this.data('content') ? $this.data('content') : $this.html(),
tokens = $this.data('tokens') ? $this.data('tokens') : null,
subtext = typeof $this.data('subtext') !== 'undefined' ? '<small class="text-muted">' + $this.data('subtext') + '</small>' : '',
icon = typeof $this.data('icon') !== 'undefined' ? '<span class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></span> ' : '',
img = typeof $this.data('img') !== 'undefined' ? '<img class="my-logo" src="' + $this.data('img') + '"> ' : '', //添加img
$parent = $this.parent(),
isOptgroup = $parent[0].tagName === 'OPTGROUP',
isOptgroupDisabled = isOptgroup && $parent[0].disabled,
isDisabled = this.disabled || isOptgroupDisabled,
prevHiddenIndex;
if (icon !== '' && isDisabled) {
icon = '<span>' + icon + '</span>';
}
if (!$this.data('content')) {
// Prepend any icon and append any subtext to the main text.
text = icon + img + '<span class="text">' + text + subtext + '</span>'; //拼接
}
这样,只要在HTML中的<option/>中加入 'data-img' 标签即可:
<select class='selectpicker'>
<option data-img="http://../123.jpg" value="val">Label</option>
</select>