【问题标题】:Change width of contenteditable div by chuncks based on text通过基于文本的块更改 contenteditable div 的宽度
【发布时间】:2021-11-06 03:22:42
【问题描述】:

我正在尝试根据 div 的内容更改 div 的宽度:
假设最初 div 的宽度为 100px,我希望它保持在该宽度,直到用户用文本填充 90px。
当它到达时,div 的宽度应该增加一个固定值。如果用户写入更多(190 像素),则 div 的宽度将再次增加。 我尝试像这样使用 div 的 clientWidth:

get style(): string {
    if (!this.el) {
      return `
      width: 100px;
      line-height: ${DEFAULT_HEIGHT}px;
      max-height: inherit;
    `;
    }
    let divWidth = 100;
    const maxWidth = window.innerWidth - SCROLLBAR_WIDTH;
    while (this.el.clientWidth > divWidth * 0.9 && divWidth < maxWidth) {
      const width = width + 100
      if (width > maxWidth) {
        break;
      }
      divWidth = width;
    }
    return `
    width: ${divWidth}px;
    line-height: ${DEFAULT_HEIGHT}px;
    max-height: inherit;
  `;
  } 

但它确实将 div 的宽度与其自身进行比较,而不是 div 的内容。

提前致谢,

【问题讨论】:

    标签: javascript css typescript


    【解决方案1】:

    您可以关联此答案以获取内容宽度:https://stackoverflow.com/a/47224153/12933115

    我的建议是您像这样使用两个嵌套的 DIV:

    <div id="container">
        <div id="content"></div>
    </div>
    <input id="txtBox" />
    

    div#container 具有固定大小,而 div#content 则没有。

    #container {
        width: 100px;
    }
    #content {
        max-width: fit-content;
        max-width: -moz-fit-content; /* For Mozilla Firefox */
    }
    

    现在,您检测的是打字而不是宽度。然后,检查事件侦听器中内部 DIV 的宽度。

    const input = document.getElementById("txtBox");
    input.addEventListener("input", () => {
       // Check the width of the inner DIV (#content) here...
       // If the width of the inner width exceeds your limit, then you change the width
       // of the container DIV (#container).
    });
    

    以上是一般性的解释。您将根据自己的需要弄清楚如何应用它。

    【讨论】:

      猜你喜欢
      • 2014-11-28
      • 2015-03-03
      • 1970-01-01
      • 2014-03-21
      • 2011-07-31
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多