Javascript 带有标志的 Html 国家/地区列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5409780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:04:32  来源:igfitidea点击:

Html Country List with flags

javascripthtmlcountry

提问by Mr.B

I am looking for a way to select and display a list of countries, preferably with flags. Any suggestions?

我正在寻找一种选择和显示国家/地区列表的方法,最好带有标志。有什么建议?

I started of by trying this jQuery plugin http://www.graphicpush.com/website-language-dropdown-with-jquery, but as the list of countries I have is quite large it turned out that the performance was really bad (too many http requests to images). Also the list is bulky when it is larger than 50 elements.

我首先尝试了这个 jQuery 插件http://www.graphicpush.com/website-language-dropdown-with-jquery,但是由于我拥有的国家/地区列表非常大,结果证明性能非常糟糕(太许多对图像的 http 请求)。当列表大于 50 个元素时,列表也很庞大。

回答by roberkules

Just wanted to suggest a (imho) smarter way of doing the flags sprite.

只是想建议一种(恕我直言)更聪明的方式来做标志精灵。

The idea is to save the flags in a grid according to the country iso2 code.

这个想法是根据国家/地区iso2代码将标志保存在网格中。

1st letter -> vertical position
2nd letter -> horizontal position

第一个字母 -> 垂直位置
第二个字母 -> 水平位置

Examples (for 16x11px flags + 4x4px spacing):

示例(对于 16x11px 标志 + 4x4px 间距):

Austria = AT
A = 1   => vertically 1st row       => y = (1-1)*(11+4)  = 0
T = 20  => horizontally 20th column => x = (20-1)*(16+4) = 380

United States = US
U = 21  => vertically 21st row      => y = (21-1)*(11+4) = 300
S = 19  => horizontally 19th column => x = (19-1)*(16+4) = 360

This way I can calculate the flag location with a very easy function on the client side without the need of 200+ extra style definitions.

通过这种方式,我可以在客户端使用一个非常简单的函数计算标志位置,而无需 200 多个额外的样式定义。

Sample jQuery plugin:

示例 jQuery 插件:

(function($) {
    // size = flag size + spacing
    var default_size = {
        w: 20,
        h: 15
    };

    function calcPos(letter, size) {
        return -(letter.toLowerCase().charCodeAt(0) - 97) * size;
    }

    $.fn.setFlagPosition = function(iso, size) {
        size || (size = default_size);

        return $(this).css('background-position',
            [calcPos(iso[1], size.w), 'px ', calcPos(iso[0], size.h), 'px'].join(''));
    };
})(jQuery);

Demo Usage:

演示用法:

$('.country i').setFlagPosition('es');

http://jsfiddle.net/roberkules/TxAhb/

http://jsfiddle.net/roberkules/TxAhb/

And here my flag sprite:

这里是我的旗帜精灵:

enter image description here

在此处输入图片说明

回答by Ricardo Tomasi

Note from the future: jQuery UI autocomplete now supports custom rendering by default, see http://api.jqueryui.com/autocomplete/#method-_renderItem.

未来注意事项:jQuery UI 自动完成现在默认支持自定义渲染,请参阅 http://api.jqueryui.com/autocomplete/#method-_renderItem

It's pretty easy. Things you need:

这很容易。你需要的东西:

  1. jQuery UI auto-complete
  2. UI auto-complete html extension
  3. A list of country names/codes
  4. A CSS sprite with all flags
  1. jQuery UI 自动完成
  2. UI 自动完成 html 扩展
  3. 一个国家的名称/代码列表
  4. 一个CSS精灵与全旗

Remember, Google is your friend. Blend the ingredients well, carefully whisk some javascript in, and it's done - in 7 lines of code:

请记住,Google 是您的朋友。把配料混合好,小心地加入一些 javascript,就完成了 - 用 7 行代码:

var countries = [["Argentina", "ar"], ...];

var countryNames = countries.map(function(country){
  return {
      label: '<div class="flag '+country[1].toLowerCase()+'">'+country[0]+'</div>',
      value: country[0]
  }
});

$('#country').autocomplete({
  source: countryNames,
  html: true
});

Here's this code in action

这是正在运行的代码

回答by josh3736

As mentioned by commenters, a CSS sprite is the proper solution here. Fortunately, there are many CSS sprites of flags freely available. This onelooks pretty good.

正如评论者所提到的,CSS sprite 是这里的正确解决方案。幸运的是,有许多免费的标志的 CSS 精灵可用这个看起来很不错。

We will have to tweak the dropdown code to accomodate that pre-made CSS sprite. I've gone ahead and done that for you. Here's a live demo.

我们将不得不调整下拉代码以适应预先制作的 CSS 精灵。我已经为你做到了。 这是一个现场演示。

languageswitcher.js

语言切换器.js

@@ -44,10 +44,11 @@
        source.removeAttr("autocomplete");
        var selected = source.find("option:selected");
        var options = $("option", source);
-       $("#country-select").append('<dl id="target" class="dropdown"></dl>')
-       $("#target").append('<dt class="' + selected.val() + '"><a href="#"><span class="flag"></span><em>' + selected.text() + '</em></a></dt>')
-       $("#target").append('<dd><ul></ul></dd>')
+        $("#country-select").append('<dl id="target" class="dropdown f16"></dl>')
+        $("#target").append('<dt><a href="#"><em class="flag ' + selected.val().toLowerCase() + '">' + selected.text() + '</em></a></dt>');
+        $("#target").append('<dd><ul></ul></dd>');
+        var $drop = $("#target dd ul");
        options.each(function(){
-           $("#target dd ul").append('<li class="' + $(this).val() + '"><a href="' + $(this).attr("title") + '"><span class="flag"></span><em>' + $(this).text() + '</em></a></li>');
+            $drop.append('<li><a href="' + $(this).attr("title") + '"><em class="flag ' + $(this).val().toLowerCase() + '">' + $(this).text() + '</em></a></li>');
            });
    }

languageswitcher.css

语言切换器.css

@@ -45,6 +45,8 @@

 .dropdown dd { position: relative; }

+.dropdown ul { max-height:350px; overflow-y:auto; overflow-x:hidden; }
+
 .dropdown a {
    text-decoration: none;
    outline: 0;
@@ -52,6 +54,7 @@
    display: block;
    width: 130px;
    overflow: hidden;
+    white-space:nowrap;
    }

 .dropdown dt a {
@@ -107,23 +110,6 @@
        padding: 2px 10px;
        }

-   .dropdown dd ul li a span,
-   .dropdown dt a span {
-       float: left;
-       width: 16px;
-       height: 11px;
-       margin: 2px 6px 0 0;
-       background-image: url(flags.png);
-       background-repeat: no-repeat;
-       cursor: pointer;
-       }
-
-       .us a span { background-position: 0 0 }
-       .uk a span { background-position: -16px 0 }
-       .fr a span { background-position: -32px 0 }
-       .de a span { background-position: -48px 0 }
-       .nl a span { background-position: -64px 0 }
-
    .dropdown dd ul li a em,
    .dropdown dt a em {
        font-style: normal;
@@ -138,3 +124,5 @@

        .dropdown dd ul li a:hover { background-color: rgba(255,255,255,.1); }
        .dropdown dd ul li a:hover em { color: #fff; }
+
+.flag { padding-left:18px; }

The CSS changes I made were Q&D hacks; you'll probably want to spend some time polishing them. I removed all of the flag-specific stuff from languageswitcher.css since we're using flag16.css.

我所做的 CSS 更改是 Q&D hacks;你可能想花一些时间来打磨它们。我从 languageswitcher.css 中删除了所有特定于标志的东西,因为我们使用的是flag16.css

Also, if the country code doesn't exist in the CSS sprite, the flag shown will default to the African Union's flag since it is the first image in the sprite. In the demo, several of the countries in my example list don't have a sprite image. Watch out for that.

此外,如果 CSS 精灵中不存在国家/地区代码,则显示的旗帜将默认为非洲联盟的旗帜,因为它是精灵中的第一个图像。在演示中,我的示例列表中的几个国家/地区没有精灵图像。请注意这一点。

回答by Pepe

Here's a file with the list of countries and links to their flags (some of the links might not be working though but most of them are) Excel File

这是一个文件,其中包含国家/地区列表及其旗帜的链接(尽管其中一些链接可能无效,但大多数链接有效) Excel 文件

回答by Anil

You can also use flags from http://www.famfamfam.com/lab/icons/flags/and simply use CSS for positioning the appropriate flag.

您还可以使用来自http://www.famfamfam.com/lab/icons/flags/ 的标志,并简单地使用 CSS 来定位适当的标志。

----EDITED----

----编辑----

If i need to show flag of my country then i would do mapping from CSS like

<span class='np'></span>

.np {
background: url(./flags_preview_large.png) -172px -397px no-repeat;
width: 14px;
height: 20px;
}

如果我需要显示我国家的国旗,那么我会从 CSS 中进行映射,例如

<span class='np'></span>

.np {
background: url(./flags_preview_large.png) -172px -397px no-repeat;
width: 14px;
height: 20px;
}