js to calc string width in font-size 15px p tag the string may contain CJK characters
To calculate the width of a string in JavaScript, you can create a hidden <p> element with the specified font size, insert the string into it, and then measure the width of the element using the offsetWidth property. Here's an example that works for both Latin and CJK characters:
function calculateStringWidth(string) {
// Create a hidden <p> element
const p = document.createElement('p');
p.style.fontSize = '15px';
p.style.visibility = 'hidden';
p.style.position = 'absolute';
p.style.whiteSpace = 'nowrap';
p.style.fontFamily = 'Arial'; // Use the desired font family
// Insert the string into the <p> element
p.textContent = string;
// Append the <p> element to the document body
document.body.appendChild(p);
// Measure the width of the <p> element
const width = p.offsetWidth;
// Remove the <p> element from the DOM
document.body.removeChild(p);
// Return the width
return width;
}
// Usage example
const string = '你好,Hello';
const width = calculateStringWidth(string);
console.log(`Width of "${string}": ${width}px`);
In this example, the calculateStringWidth function takes a string as input and returns the width of the string in pixels. The function creates a hidden <p> element with a font size of 15 pixels, inserts the string into it, appends the element to the document body, measures its width using offsetWidth, removes the element from the DOM, and finally returns the width. The calculateStringWidth function is then used to calculate the width of the example string "你好,Hello" and log it to the console
原文地址: https://www.cveoy.top/t/topic/hzMH 著作权归作者所有。请勿转载和采集!