Skip to content

Instantly share code, notes, and snippets.

@codingmiao
Created February 13, 2017 08:50
Show Gist options
  • Save codingmiao/af5b9dacf8d80d354aa164e346e91fd7 to your computer and use it in GitHub Desktop.
Save codingmiao/af5b9dacf8d80d354aa164e346e91fd7 to your computer and use it in GitHub Desktop.
js获取输入文本的大小
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Title</title>
</head>
<script src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
<body>
<span id="ruler"></span><-- add ' style="visibility: hidden;" ' to hidden it<br/>
input text:<input type="text" id="ipt"/><br/>
fontSize:<input type="text" id="sizeIpt" value="13"/>px<br/>
font:<input type="text" id="fontIpt" value="微软雅黑"/><br/>
<button onclick="getTextWidth()">getTextWidth</button>
<br/>
<span id="res"></span>
<script>
var ruler = $("#ruler");
var ruler0 = ruler[0];
var style = document.getElementById("ruler").style;
function getTextWidth() {
var text = document.getElementById('ipt').value;
ruler.text(text);
var fz = document.getElementById('sizeIpt').value + 'px';
style.fontSize = fz;
style.fontFamily = document.getElementById('fontIpt').value;
var len = ruler0.offsetWidth;
document.getElementById('res').innerHTML = len;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment