codingmiao
2/13/2017 - 8:50 AM

js获取输入文本的大小

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>