简体   繁体   中英

How to append text to div

Hi i have written this code to take 3 parameters and assign to variable.now i want to append the text i am getting throughparameter to div fontdiv how to do this?

here is what i have tried..

function getTextWidth(text, fontname, fontsize) {
    var elem = '<div id="fontdiv" style="position: absolute;visibility: visible;height: auto;"></div>';
    $('body').append($(elem));
    var fontdiv = document.getElementById('fontdiv');
    fontdiv.style.fontSize = fontsize;
    fontdiv.style.fontFamily = fontname;
    $("#fontdiv").html($('text').val());
    return fontdiv.clientWidth;
};

如果您的text参数已经有文字

$("#fontdiv").append(text);    // append text into fontdiv

Replace

$('body').append($(elem));

with

$('body').append(elem);

Use

function getTextWidth(text, fontname, fontsize) {
    var elem = '<div id="fontdiv" style="position: absolute;visibility: visible;height: auto;"></div>';
    var el = $(elem).append(text);
    $('body').append(el);
    var fontdiv = document.getElementById('fontdiv');
    fontdiv.style.fontSize = fontsize;
    fontdiv.style.fontFamily = fontname;
    $("#fontdiv").html($('text').val());
    return fontdiv.clientWidth;
};

Another way could be

function getTextWidth(text, fontname, fontsize) {
    var el = $('<div>', {
        id: 'fontdiv'
    }).css({
        position: 'absolute',
        visibility: 'visible',
        height: 'auto',
        fontSize: fontsize,
        fontFamily: fontname
    }).append(text).appendTo('body');
    return el.get(0).clientWidth;
};

If the value of text is set already (and it seems to be), use :

$("#fontdiv").append(text);

And it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM