jQuery选择样式自动宽度

时间:2012-10-28 00:42:03

标签: jquery select width option

我正在使用此选择样式脚本:http://www.bulgaria-web-developers.com/projects/javascript/selectbox/

有没有办法让新的选择器div宽度适应文本长度?目前它必须是css中定义的宽度。

droplist也一样吗?

我已经尝试过调整css,但我认为它可能只适用于jquery,但我不知道如何编辑文件以使其正常工作。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这是一个适合您的实现。 http://jsfiddle.net/mq3g4/4/

$("#country_id").selectbox({
    onOpen: function (inst) {
        //there is no onCreated handler, so I have to use this.
        //but if you want you can just fire this somewhere else
        go();
        //console.log("open", inst);
    },
    onClose: function (inst) {
        //console.log("close", inst);
    },
    onChange: function (val, inst) {
        console.log(val);
    },
    effect: "slide"
});

function go(){
    var widestLI = 0;
    //iterate through each LI and get the widest one
    $(".sbOptions > li").each(function(){
        var tmpWidth = $(this).textWidth();
        if (tmpWidth > widestLI) widestLI = tmpWidth;
        console.log(widestLI);
    });
    //now set both these elements to the widest width, plus 20px because of the padding
    $(".sbOptions, .sbHolder").width(widestLI+20);
}

//from http://stackoverflow.com/questions/1582534/calculating-text-width-with-jquery    
//this here gets the width of the html element.                                      
$.fn.textWidth = function(){
    var html_calc = $('<span>' + $(this).html() + '</span>');
    html_calc.css('font-size',$(this).css('font-size')).hide();
    html_calc.prependTo('body');
    var width = html_calc.width();
    html_calc.remove();
    return width;
}​