Created
February 13, 2017 08:50
-
-
Save codingmiao/af5b9dacf8d80d354aa164e346e91fd7 to your computer and use it in GitHub Desktop.
js获取输入文本的大小
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
<!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