项目作者: ozluy

项目描述 :
Function that calculates width of typed text. Auto calculate input width.
高级语言: JavaScript
项目地址: git://github.com/ozluy/calculate-text-width.git
创建时间: 2020-03-05T19:42:42Z
项目社区:https://github.com/ozluy/calculate-text-width

开源协议:MIT License

下载


Calculate Text Width

Function that calculates width of typed text

npm version
npm download

Code Sandbox Demo

How to use

  1. import calculateTextWidth from "calculate-text-width";
  2. /*
  3. requires two props "value" and "font"
  4. - defaultFont: normal 500 14px sans-serif
  5. */
  6. const calculatedWidth = calculateTextWidth('calculate my width', 'normal 500 14px sans-serif')
  7. console.log(calculatedWidth) // 114.37890625

How to use with React

  1. import React, { useState, useMemo } from "react"
  2. import calculateTextWidth from "calculate-text-width"
  3. export default () => {
  4. const [value, setValue] = useState("change me")
  5. return (
  6. <>
  7. <h1>Calcule Text Width</h1>
  8. <input
  9. style={{
  10. width: `${calculateTextWidth(value)}px`,
  11. font: "normal 500 14px sans-serif"
  12. }}
  13. value={value}
  14. type="text"
  15. onChange={evt => setValue(evt.target.value)}
  16. />
  17. </>
  18. )
  19. }

Thank you

Yusuf Özlü