我为表的所有tds应用了一个全局样式overflow: hidden
,除了那些带有自定义select元素作为其子元素的表。
片段: 的CSS:
th, td {
text-overflow: ellipsis;
overflow: hidden;
}
HTML:
<td>
<select class="ks-selectList">
<option>data 1.2</option>
<option>data 2.2</option>
<option>data 3.2</option>
</select>
</td>
的javascript:
// Iterate over each select element
$('.ks-selectList').each(function () {
// Cache the number of options
var $this = $(this),
numberOfOptions = $(this).children('option').length;
$this.css("visibility", "hidden");
// Wrap the select element in a div
$this.wrap('<div class="select"></div>');
// Insert a styled div to sit over the top of the hidden select element
$this.after('<div class="select-content"></div>');
// Cache the styled div
var $styledSelect = $this.next('div.select-content');
// Show the first select option in the styled div
$styledSelect.wrapInner('<span>'+$this.children('option').eq(0).text()+'</span>');
// Insert an unordered list after the styled div and also cache the list
var $list = $('<ul />', {
'class': 'options'
}).insertAfter($styledSelect);
// Insert a list item into the unordered list for each select option
for (var i = 0; i < numberOfOptions; i++) {
$('<li />', {
text: $this.children('option').eq(i).text(),
rel: $this.children('option').eq(i).val()
}).appendTo($list);
}
// Cache the list items
var $listItems = $list.children('li');
// Show the unordered list when the styled div is clicked (also hides it if the div is clicked again)
$styledSelect.click(function (e) {
e.stopPropagation();
$('div.select-content.active').each(function () {
$(this).removeClass('active').next('ul.options').hide();
});
$(this).toggleClass('active').next('ul.options').toggle();
});
// Hides the unordered list when a list item is clicked and updates the styled div to show the selected list item
// Updates the select element to have the value of the equivalent option
$listItems.click(function (e) {
e.stopPropagation();
$styledSelect.text($(this).text()).removeClass('active');
$this.val($(this).attr('rel'));
$list.hide();
});
// Hides the unordered list when clicking outside of it
$(document).click(function () {
$styledSelect.removeClass('active');
$list.hide();
});
});
结果: screenshot #1
预期结果: screenshot #2
我知道我可以使用类覆盖它,但是我想在不使用类的情况下执行此操作。