开发者

jQuery val not working properly in Chrome

开发者 https://www.devze.com 2023-01-01 19:39 出处:网络
I have a simple jQuery function: $(\'开发者_运维知识库#selectable1 span\').live(\'mousedown\', function() {

I have a simple jQuery function:

$('开发者_运维知识库#selectable1 span').live('mousedown', function() {
        var ff = $(this).css("font-family");
        $("#family").val(ff);
});

When a span element is clicked (mousedown) an input (#family) gets its font family value. It works in FireFox but in Chrome it works only for font families composed from only one word. Georgia will work but Times New Roman will not.

You can see the code here:

http://jsfiddle.net/aLaGa/

or live at http://www.typefolly.com

What is wrong with this? Thanx


Chrome wraps font families having multiple words with single quotes. So the value for font-family returned in Chrome is: 'Times New Roman' which does not match the value in the select list Times New Roman.

Considering all these browser variations, I think the best solution is to split apart the family names by comma, trim the single quote (if any) around each font name, and join them later. Use this sanitized value inside the select list.

$('#selectable1 span').live('mousedown', function() {
    var fontFamily = $(this).css('font-family');

    var fonts = fontFamily.split(',');
    var sanitizedFonts = $.map(fonts, function(name) {
        // trim single quotes around font name (if any) for Chrome/Safari
        // trim double quotes around font name (if any) for Firefox
        return name.trim().replace(/^['"]|['"]$/g, '');
    });

    $('#family').val(sanitizedFonts.join(', '));
});

See an example. The select list had to be changed to follow this consistent naming scheme for values:

fontName[, fontName]

This heavily relies on the fact that a font-name will not contain any commas, quoted or unquoted.


You can change your script slightly to replace the quotes that WebKit adds when the font name contains spaces, like this:

$('#selectable1 span').live('mousedown', function() {
  var ff = $(this).css("font-family").replace(/\'/g,"");
  $("#family").val(ff);
});    ​

You can see a working demo here :)

And here's a RegEx approach pulling the literal value out of style that's probably easier than anything, but I'm not a RegEx guru, someone feel free to improve this and update the answer (I suck at RegEx, sorry!) This works for all examples you have.


Font-family gives a list of comma separated values, not the font in use. It also may give the value in quotes. On your sample page, adding the line alert(ff) gives:

'Times New Roman'

Georgia

adage-script-1, adage-script-2

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号