How to achieve two different alignments inside a html option tag?

喜欢而已 提交于 2019-12-06 10:48:34

I faced this issue once and what I did was format the text in a monospaced font and fill the middle with spaces to seperate the text and make each row an even number of characters.

Try something like this

select {width:100px;}
.name  {float:left;}
.code  {float:right;}

modify the select box with javascript:

find the longest country name, then modify every option so there are enough spaces between country name and calling code.

Mono-spacing is the correct answer but.... you can get pretty close (not perfect) using some jQuery to repeatedly measure a text string in a hidden span.

var list = [ ["Afghanistan","+93"], ["Albania","+355"], ["Algeria","+213"] ] ;
var max = 0;
for (n = 0; n < list.length; n++)
{
    var s = list[n][0] + "..." + list[n][1]; 
    $('#dummy').html(s);
    var x = $('#dummy')[0].offsetWidth;
    list[n].push(x);
    if (max < x) max = x;
}

for (n = 0; n < list.length; n++)
{
    var fill = max - list[n][2];
    var s = "...";
    while (true)
    {
        $('#dummy').html(s);
        var x = $('#dummy')[0].offsetWidth;
        if (fill <= x) break;
        s += ".";
    }
    var html = list[n][0] + s + list[n][1];
    $('#countryCallingCode').append($('<option></option').val(n+1).html(html));     
}

Here's a mono-space JS solution to go along with Scott Evernden's JQuery example. I only tested it in Firefox, but this should be enough to start with.

The JavaScript

var MIN_SPACES_BETWEEN_VALS = 3;

function mkOption(left, right, total)
{
    var str = left;
    var spaces = total - left.length - right.length;
    for(x = 0;x < spaces;x++)
        str += "\xA0";

    var opt = document.createElement("option");
    opt.text = str + right;
    opt.value = right;
    return opt;
}

function populate(selId, vals)
{
    var sel = document.getElementById(selId);

    var maxLeft = -1;
    var maxRight = -1;
    for(idx = 0;idx < vals.length;idx++)
    {
        if(vals[idx][0].length > maxLeft)
            maxLeft = vals[idx][0].length;

        if(vals[idx][1].length > maxRight)
            maxRight = vals[idx][1].length;
    }

    var total = maxLeft + maxRight + MIN_SPACES_BETWEEN_VALS;
    for(idx = 0;idx < vals.length;idx++)
        sel.add(mkOption(vals[idx][0], vals[idx][1], total), null);   
}

The HTML

<html>

    <head>
        <script src="selectTest.js">

        </script>
        <style>
            select
            {   
               font-family: Courier, mono;
            }
        </style>
    </head>

    <body>

        <select name="countryCallingCode" id="countryCallingCode">
        </select>
        <script>
            var vals = [["Afghanistan", "+93"], ["Albania", "+355"], ["Algeria", "+213"]];
            populate("countryCallingCode", vals);
        </script>

    </body>

</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!