要计算文本宽度,请使用JavaScript中的Canvas.measureText()方法。您可以尝试运行以下代码以获取文本宽度-
<!DOCTYPE html> <html> <head> </head> <body> <script> function displayTextWidth(text, font) { var myCanvas = displayTextWidth.canvas || (displayTextWidth.canvas = document.createElement("canvas")); var context = myCanvas.getContext("2d"); context.font = font; var metrics = context.measureText(text); return metrics.width; }; document.write("Text Width: "+displayTextWidth("这是演示文字!", "italic 18pt verdana")); // </script> </body> </html>