Getting the CSS-transformed value of an input via JavaScript

后端 未结 4 648
迷失自我
迷失自我 2021-01-06 03:38

Consider the following scenario:

HTML




        
4条回答
  •  逝去的感伤
    2021-01-06 03:56

    Copying the CSS-transformed value from source to target won't work because the value hasn't actually changed, only the styling has. Other style attributes (like font-family, or color) would not transfer; text-transform will behave in the same limited way.

    If you want to actually change the value of the string, which it sounds like you do, you will need to use JavaScript, possibly with RegExp.

    Instead of this...

    element('target').value = element('source').value;
    

    ...this short bit of code should do exactly what you need:

    element('target').value = element('source').value.replace(/(\b\w)/g, function (m, p1) {
         return p1.toUpperCase();
    });
    

    JSFiddle demonstration here.

    SHORT EXPLANATION: The \b at the beginning of the RegExp looks for the beginning of any word and the \w (because it's captured inside the parentheses) captures any single alphanumeric character in that position. This is then stored in the argument p1 for the function, which merely returns a capitalised version.

提交回复
热议问题