Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - Superscript in input field of text type

I have a HTML input field like this:

<input id="op" type="text" value="0" />

I want to update the value of this field dynamically with some string containing superscript. It did not work and I tried this.

document.getElementById("op").value="a<sup>3</sup>" //don't work
document.getElementById("op").innerHTML="a<sup>3</sup>" //don't work

How can I get this to work? I could have tried to figure the rest myself but since I am already forced to ask this, I would like to tell what I am planning to do.

 var x=3; var y=2;
 document.getElementById("op").innerHTML="a<sup> x-y </sup>";
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about a plugin:

$.fn.superScript = function() {
    var chars = '+?=()0123456789Aa???ɑ?Bbc?DdeEe?????fGgɡ?hH?Ii????jJ??KklL???Mm?Nn????Oo?????Pp?rR???s??Tt?Uu???????vV??wWxyz?????βγδθφχн???',
        sup   = '??????123???????????????????????????????????????????????????????????????????????????????????????????????????????????????????';

    return this.each(function() {
        this.value = this.value.replace(/<sup[^>]*>(.*?)</sup>/g, function(x) {
            var str = '',
                txt = $.trim($(x).unwrap().text());

            for (var i=0; i<txt.length; i++) {
                var n = chars.indexOf(txt[i]);
                str += (n!=-1 ? sup[n] : txt[i]);
            }
            return str;
        });
    });
}

called like:

$('input').superScript();

Could probably be bound to keyup etc as well, and rather easily converted to plain javascript and not jQuery, but I just made it, so if it works, modify it to suit your needs ?

FIDDLE


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...