HTML:
Please select an item
Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more
CSS:
.shortenedSelect {
max-width: 350px;
}使用Javascript:
// Shorten select option text if it stretches beyond max-width of select element
$.each($('.shortenedSelect option'), function(key, optionElement) {
var curText = $(optionElement).text();
$(this).attr('title', curText);
// Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system.
var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10)/7.3);
if (curText.length > lengthToShortenTo) {
$(this).text('... ' + curText.substring((curText.length - lengthToShortenTo), curText.length));
}
});
// Show full name in tooltip after choosing an option
$('.shortenedSelect').change(function() {
$(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title')));
});完美的工作。我自己也有同样的问题。看看这个JSFiddle http://jsfiddle.net/jNWS6/426/