Created
May 10, 2020 23:29
-
-
Save keidrun/c86608db2f7e0d802ece775e1effefc2 to your computer and use it in GitHub Desktop.
Calculate the text width using jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
var $target = $('#target'); | |
var text = $target.text(); | |
text.split('').forEach((str) => { | |
console.log(str + "'s length is " + textWidth($target, str)); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Calculate the width of the text in the element | |
* @param {jQuery Object} element - the element | |
* @param {string} text - the text in the element | |
* @returns {float} the text width | |
*/ | |
function textWidth(element, text) { | |
$element = $(element); | |
var span = $('<span>').hide().append(text); | |
$element.append(span); | |
var width = span.width(); | |
$element.find('span:first').remove(); | |
return width; | |
} | |
// Just a bit refer to https://stackoverflow.com/questions/1582534/calculating-text-width |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment