最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create a font selection bar in html - Stack Overflow

programmeradmin5浏览0评论

I want to create a drop-down menu in which we can see all the available fonts and we can select any font of our choice. Also I want to create a font-color selection widget. There exists a large no of font-styles. I want to know how do i get all these fonts and how to create a widget using which user can select the color of his choice.

For creating font-selection drop-down menu, I have used list and for demo purpose, i added 3-4 font names and displaying them. Its working fine. Google gave me the list of all font-names but writing down in html code isn't a good approach i think. I guess there should exist a js library for doing all this. Is there ?

I want to create a drop-down menu in which we can see all the available fonts and we can select any font of our choice. Also I want to create a font-color selection widget. There exists a large no of font-styles. I want to know how do i get all these fonts and how to create a widget using which user can select the color of his choice.

For creating font-selection drop-down menu, I have used list and for demo purpose, i added 3-4 font names and displaying them. Its working fine. Google gave me the list of all font-names but writing down in html code isn't a good approach i think. I guess there should exist a js library for doing all this. Is there ?

Share Improve this question asked Apr 19, 2012 at 10:05 Sachin JainSachin Jain 21.8k34 gold badges110 silver badges176 bronze badges 2
  • This smells like you're trying to develop a rich text editor on some level. Don't reinvent the wheel. – MetalFrog Commented Apr 19, 2012 at 11:59
  • 2 You could have fun with google font api :P jsfiddle/rlemon/ENpWt – rlemon Commented Apr 19, 2012 at 12:58
Add a ment  | 

4 Answers 4

Reset to default 8

Probably overkill... but here is a font selector example I came up with using Google Font API and a Document Fragment Builder script I wrote a while ago.

var FragBuilder = (function() {
    var applyStyles = function(element, style_object) {
        for (var prop in style_object) {
            element.style[prop] = style_object[prop];
        }
    };
    var generateFragmentFromJSON = function(json) {
        var tree = document.createDocumentFragment();
        json.forEach(function(obj) {
            if (!('tagName' in obj) && 'textContent' in obj) {
                tree.appendChild(document.createTextNode(obj['textContent']));
            } else if ('tagName' in obj) {
                var el = document.createElement(obj.tagName);
                delete obj.tagName;
                for (part in obj) {
                    var val = obj[part];
                    switch (part) {
                    case ('textContent'):
                        el.appendChild(document.createTextNode(val));
                        break;
                    case ('style'):
                        applyStyles(el, val);
                        break;
                    case ('childNodes'):
                        el.appendChild(generateFragmentFromJSON(val));
                        break;
                    default:
                        if (part in el) {
                            el[part] = val;
                        }
                        break;
                    }
                }
                tree.appendChild(el);
            } else {
                throw "Error: Malformed JSON Fragment";
            }
        });
        return tree;
    };
    var generateFragmentFromString = function(HTMLstring) {
        var div = document.createElement("div"),
            tree = document.createDocumentFragment();
        div.innerHTML = HTMLstring;
        while (div.hasChildNodes()) {
            tree.appendChild(div.firstChild);
        }
        return tree;
    };
    return function(fragment) {
        if (typeof fragment === 'string') {
            return generateFragmentFromString(fragment);
        } else {
            return generateFragmentFromJSON(fragment);
        }
    };
}());

function jsonp(url) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    document.getElementsByTagName('body')[0].appendChild(script);
}

function replacestyle(url) {
    if (!document.getElementById('style_tag')) {
        var style_tag = document.createElement('link');
        style_tag.rel = 'stylesheet';
        style_tag.id = 'style_tag';
        style_tag.type = 'text/css';
        document.getElementsByTagName('head')[0].appendChild(style_tag);
        replacestyle(url);
    }
    document.getElementById('style_tag').href = url;
}

function loadFonts(json) {
    var select_frag = [
        {
        'tagName': 'select',
        'id': 'font-selection',
        'childNodes': [
            {
            'tagName': 'option',
            'value': 'default',
            'textContent': 'Default'}
        ]}
    ];
    json['items'].forEach(function(item) {
        var family_name = item.family,
            value = family_name.replace(/ /g, '+');

        if (item.variants.length > 0) {
            item.variants.forEach(function(variant) {
                value += ':' + variant;
            });
        }

        select_frag[0].childNodes.push({
            'tagName': 'option',
            'value': value,
            'textContent': family_name
        });
    });

    document.getElementById('container').appendChild(FragBuilder(select_frag));
    document.getElementById('font-selection').onchange = function(e) {
        var font = this.options[this.selectedIndex].value,
            name = this.options[this.selectedIndex].textContent;
        if (font === 'default') {
            document.getElementById('sink').style.fontFamily = 'inherit';
        } else {
            document.getElementById('sink').style.fontFamily = name;
            replacestyle('https://fonts.googleapis./css?family=' + font);
        }
    };
}

jsonp("https://www.googleapis./webfonts/v1/webfonts?key=AIzaSyDBzzPRqWl2eU_pBMDr_8mo1TbJgDkgst4&sort=trending&callback=loadFonts");​

Here is the Kitchen Sink example...

Jukka K. Korpela is right, but regarding your question:

This should get you started on the selecting font family:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <h1 id="liveh1">Some text</h1>
  <select id="selecth1FontFamily" name="selectFontFamily" onchange="updateh1family();">
    <option> Serif </option>
    <option> Arial </option>
    <option> Sans-Serif </option>                                  
    <option> Tahoma </option>
    <option> Verdana </option>
    <option> Lucida Sans Unicode </option>                               
  </select>
    <script>
      function updateh1family() {
        var selector = document.getElementById('selecth1FontFamily');
        var family = selector.options[selector.selectedIndex].value;
        var h1 = document.getElementById('liveh1')
        h1.style.fontFamily = family;        
      }

    </script>
</body>
</html>

If it's important to see if the fonts are installed you can use this to tool to check. And if it's ok to use flash you may use something like font-detect-js (they also have a demo but I didn't manage to get it to work in chrome).

And for color selector I would reend using : jscolor

Hope it helps, and good luck!

I have created a jquery library for displaying all the google fonts in a drop-down list with instant preview. https://github./saadqbal/HiGoogleFonts. It has two callback methods:

  • selectedCallback - This event is triggered when a font is selected but not yet loaded.
  • loadedCallback - This event is triggered when the font is loaded and is ready to be applied. This is where you should apply font to an element.

It is possible to get all the available fonts—on IE, see http://www.cs.tut.fi/~jkorpela/listfonts1.html

But it would hardly be a good idea to offer such a list in a control meant to let the user select his preferred font. The list would practically certainly contain menu fonts that would make no sense as text fonts, such as fantasy fonts, Wingdings fonts, Symbol, and fonts with odd character repertoires.

Any list of “all font names” is either bogus or just a list of all font names under some very specific conditions.

The best way to let the user select a font of his preference is that you do not set font family at all, letting browser settings (which are usually user-controllable) take their full effect. There are good reasons for not doing that, though (such as Times New Roman being the most mon factory default and most users not being interested in changing font settings in browsers).

发布评论

评论列表(0)

  1. 暂无评论