[英]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? 嗨,我已经编写了这段代码来接受3个参数并分配给variable.now我想追加我通过参数获取的文本到div fontdiv如何做到这一点?
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 : 如果已经设置了text的值(似乎已经设置),请使用:
$("#fontdiv").append(text);
And it should work. 它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.