Set width of dropdown element in HTML select dropdown options

后端 未结 7 1136
醉话见心
醉话见心 2020-11-27 21:36

I am working on a website that involves automatically populating a select box using a PHP script. This all works fine except the problem is that what I am using to populate

7条回答
  •  广开言路
    2020-11-27 21:59

    HTML:

    
    

    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')));
    });
    

    Works perfectly. I had the same issue myself. Check out this JSFiddle http://jsfiddle.net/jNWS6/426/

提交回复
热议问题