【问题标题】:Change font size dynamically on specific paragraph <p> elements?在特定段落 <p> 元素上动态更改字体大小?
【发布时间】:2016-02-21 06:14:27
【问题描述】:

以下 JSFiddle 将文本拆分为单独的段落 &lt;p&gt; 框,并设置文本限制。


是否可以根据 select 选项通过 contenteditable 更改框中的文本大小,同时仍然允许编辑、删除文本限制并保留动态大小属性?

更新 2:生成的所有框都需要:

“等于相同的高度和宽度”

并在字体为动态更新,需要在所有元素之间保持一致。


更新 3:最后生成的段落不等于其他具有边框大小高度的段落。


更新 4:所有段落都需要使用高度属性自动生成。当前答案的问题是最后生成的段落边框也需要与其他段落的前一个高度边框的高度相同,包括更改字体大小时。

更新 5 [图像]:最后分割的段落高度和边框不等于其他问题的示例。

链接到Fiddle

如果可以提供一个新的小提琴,将不胜感激,因为我还是编码新手。 谢谢你!

$(function() {
  $('select').on('change', function() {
    var targets = $('p'),
      property = this.dataset.property;
    targets.css(property, this.value);
  }).prop('selectedIndex', 0);
});
var btn = document.getElementById('go'),
  textarea = document.getElementById('textarea1'),
  content = document.getElementById('content'),
  chunkSize = 100;
btn.addEventListener('click', initialDistribute);
content.addEventListener('keyup', handleKey);
content.addEventListener('paste', handlePaste);

function initialDistribute() {
  var text = textarea.value;
  while (content.hasChildNodes()) {
    content.removeChild(content.lastChild);
  }
  rearrange(text);
}

function rearrange(text) {
  var chunks = splitText(text, false);
  chunks.forEach(function(str, idx) {
    para = document.createElement('P');
    para.setAttribute('contenteditable', true);
    para.textContent = str;
    content.appendChild(para);
  });
}

function handleKey(e) {
  var para = e.target,
    position,
    key, fragment, overflow, remainingText;
  key = e.which || e.keyCode || 0;
  if (para.tagName != 'P') {
    return;
  }
  if (key != 13 && key != 8) {
    redistributeAuto(para);
    return;
  }
  position = window.getSelection().getRangeAt(0).startOffset;
  if (key == 13) {
    fragment = para.lastChild;
    overflow = fragment.textContent;
    fragment.parentNode.removeChild(fragment);
    remainingText = overflow + removeSiblings(para, false);
    rearrange(remainingText);
  }
  if (key == 8 && para.previousElementSibling && position == 0) {
    fragment = para.previousElementSibling;
    remainingText = removeSiblings(fragment, true);
    rearrange(remainingText);
  }
}

function handlePaste(e) {
  if (e.target.tagName != 'P') {
    return;
  }
  overflow = e.target.textContent + removeSiblings(fragment, true);
  rearrange(remainingText);
}

function redistributeAuto(para) {
  var text = para.textContent,
    fullText;
  if (text.length > chunkSize) {
    fullText = removeSiblings(para, true);
  }
  rearrange(fullText);
}

function removeSiblings(elem, includeCurrent) {
  var text = '',
    next;
  if (includeCurrent && !elem.previousElementSibling) {
    parent = elem.parentNode;
    text = parent.textContent;
    while (parent.hasChildNodes()) {
      parent.removeChild(parent.lastChild);
    }
  } else {
    elem = includeCurrent ? elem.previousElementSibling : elem;
    while (next = elem.nextSibling) {
      text += next.textContent;
      elem.parentNode.removeChild(next);
    }
  }
  return text;
}

function splitText(text, useRegex) {
  var chunks = [],
    i, textSize, boundary = 0;
  if (useRegex) {
    var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
    chunks = text.match(regex) || [];
  } else {
    for (i = 0, textSize = text.length; i < textSize; i = boundary) {
      boundary = i + chunkSize;
      if (boundary <= textSize && text.charAt(boundary) == ' ') {
        chunks.push(text.substring(i, boundary));
      } else {
        while (boundary <= textSize && text.charAt(boundary) != ' ') {
          boundary++;
        }
        chunks.push(text.substring(i, boundary));
      }
    }
  }
  return chunks;
}
#text_land {
  border: 1px solid #ccc;
  padding: 25px;
  margin-bottom: 30px;
}
textarea {
  width: 95%;
}
label {
  display: block;
  width: 50%;
  clear: both;
  margin: 0 0 .5em;
}
label select {
  width: 50%;
  float: right;
}
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}
body {
  font-family: monospace;
  font-size: 1em;
}
h3 {
  margin: 1.2em 0;
}
div {
  margin: 1.2em;
}
textarea {
  width: 100%;
}
button {
  padding: .5em;
}
p {
  padding: 1.2em .5em;
  margin: 1.4em 0;
  border: 1px dashed #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="styles">
  <label>Font-size:
    <select data-property="font-size">
      <option disabled>
        Select font-size:
      </option>
      <option>
        smaller
      </option>
      <option>
        10px
      </option>
      <option>
        12px
      </option>
      <option>
        14px
      </option>
      <option>
        16px
      </option>
      <option>
        18px
      </option>
      <option>
        20px
      </option>
      <option>
        larger
      </option>
    </select>
  </label>
</div>
<div>
  <h3>Paste text in the field below to divide text into paragraphs..</h3>
  <textarea id="textarea1" placeholder="Type text here, then press the button below." rows="5">
  </textarea>
  <br>
  <br>
  <button id="go">Divide Text into Paragraphs</button>
</div>
<div>
  <h3 align="right">Divided Text Will Appear Below:</h3>
  <hr>
  <div id="content"></div>
</div>

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    给你JSFiddle

    $('#FontSize').change(function(){
    var fontsize = $(this).val();
    $('textarea').css('fontSize',fontsize);
    });
    

    【讨论】:

    • 但是,当在上一段中按回车添加新的动态段落时,下一段文字的大小不同。
    • 但是,是否可以保持段落的宽度和高度,只改变文本大小,所以它作为动态文本大小溢出到下一个段落?
    • 是的,但是,保留每个动态段落的段落宽度和高度限制
    • 看到这个Example,如果我理解正确你想要这个,对吧?
    • 请查看更新版本。 jsfiddle.net/InnovativeDave/n9b6wju8/6 基本上,当您使用下拉选项动态创建段落并调整大小时,文本会相互重叠,而不是流入下一个段落。
    【解决方案2】:

    我不确定我是否理解问题...您可以将字体大小设置为父元素 (#content{font-size:whatever}) 并继承它 (#content p {font-size :继承})。如果您在父项中设置字体大小,则在添加时将应用于已添加的段落和新的段落。

    (小提琴中的变化:select的变化中的选择器,“p”和“#content p”的CSS选择器/属性)

    (针对“相同高度”段落编辑的答案) 为了获得相同的高度,我添加了一个相同的高度(选择器)函数。我不确定你什么时候想触发它,我已经把它放在选择更改和重新排列(文本)上。 (希望对您有所帮助。使用 outerHeight 修复函数中的高度) ...和小提琴再次编辑:sameheight 也会在窗口调整大小事件时触发。

    function sameheight(selector){
    var max_y=0;
    var y=0;
    $(selector).css('height','');
    $(selector).each(function(){
      y=$(this).height();
      if(y>max_y) max_y=y;
    });
    $(selector).css('height',max_y);
    }
    

    $(function() {
      $('select').on('change', function() {
        //Lets target the parent element, instead of P. P will inherit it's font size (css)
        var targets = $('#content'),
          property = this.dataset.property;
        targets.css(property, this.value);
        sameheight('#content p');
      }).prop('selectedIndex', 0);
    });
    $( window ).resize(function() {
        sameheight('#content p');
    });
    var btn = document.getElementById('go'),
      textarea = document.getElementById('textarea1'),
      content = document.getElementById('content'),
      chunkSize = 100;
    btn.addEventListener('click', initialDistribute);
    content.addEventListener('keyup', handleKey);
    content.addEventListener('paste', handlePaste);
    
    function initialDistribute() {
      var text = textarea.value;
      while (content.hasChildNodes()) {
        content.removeChild(content.lastChild);
      }
      rearrange(text);
    }
    
    function rearrange(text) {
      var chunks = splitText(text, false);
      chunks.forEach(function(str, idx) {
        para = document.createElement('P');
        para.setAttribute('contenteditable', true);
        para.textContent = str;
        content.appendChild(para);
      });
      sameheight('#content p');
    }
    
    function handleKey(e) {
      var para = e.target,
        position,
        key, fragment, overflow, remainingText;
      key = e.which || e.keyCode || 0;
      if (para.tagName != 'P') {
        return;
      }
      if (key != 13 && key != 8) {
        redistributeAuto(para);
        return;
      }
      position = window.getSelection().getRangeAt(0).startOffset;
      if (key == 13) {
        fragment = para.lastChild;
        overflow = fragment.textContent;
        fragment.parentNode.removeChild(fragment);
        remainingText = overflow + removeSiblings(para, false);
        rearrange(remainingText);
      }
      if (key == 8 && para.previousElementSibling && position == 0) {
        fragment = para.previousElementSibling;
        remainingText = removeSiblings(fragment, true);
        rearrange(remainingText);
      }
    }
    
    function handlePaste(e) {
      if (e.target.tagName != 'P') {
        return;
      }
      overflow = e.target.textContent + removeSiblings(fragment, true);
      rearrange(remainingText);
    }
    
    function redistributeAuto(para) {
      var text = para.textContent,
        fullText;
      if (text.length > chunkSize) {
        fullText = removeSiblings(para, true);
      }
      rearrange(fullText);
    }
    
    function removeSiblings(elem, includeCurrent) {
      var text = '',
        next;
      if (includeCurrent && !elem.previousElementSibling) {
        parent = elem.parentNode;
        text = parent.textContent;
        while (parent.hasChildNodes()) {
          parent.removeChild(parent.lastChild);
        }
      } else {
        elem = includeCurrent ? elem.previousElementSibling : elem;
        while (next = elem.nextSibling) {
          text += next.textContent;
          elem.parentNode.removeChild(next);
        }
      }
      return text;
    }
    
    function splitText(text, useRegex) {
      var chunks = [],
        i, textSize, boundary = 0;
      if (useRegex) {
        var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
        chunks = text.match(regex) || [];
      } else {
        for (i = 0, textSize = text.length; i < textSize; i = boundary) {
          boundary = i + chunkSize;
          if (boundary <= textSize && text.charAt(boundary) == ' ') {
            chunks.push(text.substring(i, boundary));
          } else {
            while (boundary <= textSize && text.charAt(boundary) != ' ') {
              boundary++;
            }
            chunks.push(text.substring(i, boundary));
          }
        }
      }
      return chunks;
    }
    
     function sameheight(selector){
    var max_y=0;
    var y=0;
    $(selector).css('height','');
    $(selector).each(function(){
      y=$(this).outerHeight();
      if(y>max_y) max_y=y;
    });
    $(selector).css('height',max_y);
      }
    #text_land {
      border: 1px solid #ccc;
      padding: 25px;
      margin-bottom: 30px;
    }
    textarea {
      width: 95%;
    }
    label {
      display: block;
      width: 50%;
      clear: both;
      margin: 0 0 .5em;
    }
    label select {
      width: 50%;
      float: right;
    }
    * {
      box-sizing: border-box;
      padding: 0;
      margin: 0;
    }
    body {
      font-family: monospace;
      font-size: 1em;
    }
    h3 {
      margin: 1.2em 0;
    }
    div {
      margin: 1.2em;
    }
    textarea {
      width: 100%;
    }
    button {
      padding: .5em;
    }
    p {
     /*Here the sliles for OTHER paragraphs*/
    }
    #content p {
      font-size:inherit;/*So it gets the font size set on the #content div*/
      padding: 1.2em .5em;
      margin: 1.4em 0;
      border: 1px dashed #aaa;
      overflow:hidden;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="styles">
      <label>Font-size:
        <select data-property="font-size">
          <option disabled>
            Select font-size:
          </option>
          <option>
            smaller
          </option>
          <option>
            10px
          </option>
          <option>
            12px
          </option>
          <option>
            14px
          </option>
          <option>
            16px
          </option>
          <option>
            18px
          </option>
          <option>
            20px
          </option>
          <option>
            larger
          </option>
        </select>
      </label>
    </div>
    <div>
      <h3>Paste text in the field below to divide text into paragraphs..</h3>
      <textarea id="textarea1" placeholder="Type text here, then press the button below." rows="5">
      </textarea>
      <br>
      <br>
      <button id="go">Divide Text into Paragraphs</button>
    </div>
    <div>
      <h3 align="right">Divided Text Will Appear Below:</h3>
      <hr>
      <div id="content"></div>
    </div>

    【讨论】:

    • 出现的问题是导入文本时最后一个段落的边框高度不等于其他动态段落。
    • 抱歉,看不到。我看到最后一段边框与其他段落相同。你的意思是你想要所有的段落都具有相同的高度,即使这意味着较短的段落的底部会有空白?如果没有,请添加“不良”效果的截图。
    • 请参考上面的更新5。这显示了最后一个分割段落的问题。谢谢!
    • 已修复。尽管有外部高度,我仍在使用高度。现在检查:) @Dave
    • 但是,当页面重新调整大小时,文本会被隐藏,并且由于溢出属性而被隐藏。因此,是否有可能解决这个问题?谢谢!
    【解决方案3】:

    这样试试

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="styles">
        <label>Font-size: <select data-property="font-size" 
         onchange="$('#textarea1').css('font-size',this.value)">
            <option disabled>Select font-size:</option>
            <option>smaller</option>
            <option>10px</option>
            <option>12px</option>
            <option>14px</option>
            <option>16px</option>
            <option>18px</option>
            <option>20px</option>
            <option>larger</option>
        </select></label>
    </div>
    <div>
        <h3>Paste text in the field below to divide text into paragraphs..</h3>
        <textarea id="textarea1" placeholder=
        "Type text here, then press the button below." rows="5"> Test text
    </textarea><br>
        <br>
        <button id="go">Divide Text into Paragraphs</button>
    </div>

    【讨论】:

      【解决方案4】:

      相信我有你的答案:

      $(function() {
        $('select').on('change', function() {
          var targets = $('p'),
            property = this.dataset.property;
          $("#content").css({'font-size': this.value});
        }).prop('selectedIndex', 0);
      });
      

      我更改了函数以便将字体大小设置为 div 而不是段落。这是你想要的吗?因为这是我从提供的信息中收集到的。

      https://jsfiddle.net/n9b6wju8/14/

      【讨论】:

      • 但是,最后生成的段落与其他段落的大小不同。有可能解决这个问题吗?谢谢!
      • 它们的大小相同。 gyazo.com/ae6b7705e717332d5383b093c7bf0bee看我刚刚做的GIF,展示一下
      【解决方案5】:

      您可以将动态style 元素注入到 DOM 中,并使用所需的字体大小对其进行更新。您可以使用 MV* 框架来更新其内容。

      $('#FontSize').change(function(){
          var fontsize = $(this).val();
          $('#style').remove(); //yes, there are better ways to update its content
          $('head').append('<style id="style">#content { font-size: '+fontsize + '}</style>');
      });
      

      摆弄:https://jsfiddle.net/ovfiddle/m75gre8o/1/

      【讨论】:

      • 需要解决的问题是所有段落都需要等高,包括动态生成的较短的段落,调整大小时边框都等高。
      【解决方案6】:

      这应该会有所帮助:

      $('#FontSize').change(function(){ var fontsize = $(this).val(); $('textarea').css('fontSize',fontsize); });

      【讨论】:

        【解决方案7】:

        更改 div 和文本区域的字体大小:

          $(function() {
                $('select').change(function() {
                    var fontsize = $(this).val();
                    $('#textarea1').css('fontSize',fontsize);
                    $('#content').css('fontSize',fontsize);
                }).prop('selectedIndex', 0);
          });
        

        保持文本区域的高度:在 CSS 中

        textarea {
            width: 95%;
            height: 200px;
        }
        

        也使用px 代替em

        【讨论】:

        • 但是,当应用新的字体大小时,文本会发生变化。但是,在编辑其中一个段落时,文本会恢复为小字体。此外,不能再设置段落的宽度。有可能解决这个问题吗?谢谢!
        • jsfiddle.net/mgpvstqt(我的previos链接没有更新,对不起我的错)。我想我不明白你的问题,它恢复到小字体的哪一部分?是在textarea 还是content
        【解决方案8】:

        我创建了你的 fiddle 的一个分支,并编辑(添加)了 select 的事件处理程序。我在它们中添加了一些代码来维护可编辑 p 元素的字体大小。使用该参考,您可以根据您的要求应用所有样式。

        如果你觉得我的回答是对的,别忘了标记它并点赞。

        JS Fiddle Fork

          targets.parent().find('style').remove();
          $('<style>[contenteditable="true"]
          {'+property+':'+this.value+'}\n[contenteditable="true"]:focus{'+property+':'+this.value+'}</style>').prependTo(targets.parent());
          {'+property+':'+this.value+'}[contenteditable="true"]:focus{'+property+':'+this.value+'}</style>');
        

        【讨论】:

          【解决方案9】:

          试试这个

          $('#FontSize').change(function(){
          var fontsize = $(this).val();
          $('textarea, #content p').css('fontSize',fontsize);
          });
          
          $('#go').click(function(){
          var fontsize = $('#FontSize').val();
          $('#content').css('fontSize',fontsize);
            
          });
          
          
          $(function() {
              $('select').on('change', function() {
                  var targets = $('p'),
                      property = this.dataset.property;
                  targets.css(property, this.value);
              }).prop('selectedIndex', 0);
          });
          var btn = document.getElementById('go'),
              textarea = document.getElementById('textarea1'),
              content = document.getElementById('content'),
              chunkSize = 400;
          btn.addEventListener('click', initialDistribute);
          content.addEventListener('keyup', handleKey);
          content.addEventListener('paste', handlePaste);
          
          function initialDistribute() {
              var text = textarea.value;
              while (content.hasChildNodes()) {
                  content.removeChild(content.lastChild);
              }
              rearrange(text);
          }
          
          function rearrange(text) {
              var chunks = splitText(text, false);
              chunks.forEach(function(str, idx) {
                  para = document.createElement('P');
                  para.setAttribute('contenteditable', true);
                  para.textContent = str;
                  content.appendChild(para);
              });
          }
          
          function handleKey(e) {
              var para = e.target,
                  position,
                  key, fragment, overflow, remainingText;
              key = e.which || e.keyCode || 0;
              if (para.tagName != 'P') {
                  return;
              }
              if (key != 13 && key != 8) {
                  redistributeAuto(para);
                  return;
              }
              position = window.getSelection().getRangeAt(0).startOffset;
              if (key == 13) {
                  fragment = para.lastChild;
                  overflow = fragment.textContent;
                  fragment.parentNode.removeChild(fragment);
                  remainingText = overflow + removeSiblings(para, false);
                  rearrange(remainingText);
              }
              if (key == 8 && para.previousElementSibling && position == 0) {
                  fragment = para.previousElementSibling;
                  remainingText = removeSiblings(fragment, true);
                  rearrange(remainingText);
              }
          }
          
          function handlePaste(e) {
              if (e.target.tagName != 'P') {
                  return;
              }
              overflow = e.target.textContent + removeSiblings(fragment, true);
              rearrange(remainingText);
          }
          
          function redistributeAuto(para) {
              var text = para.textContent,
                  fullText;
              if (text.length > chunkSize) {
                  fullText = removeSiblings(para, true);
              }
              rearrange(fullText);
          }
          
          function removeSiblings(elem, includeCurrent) {
              var text = '',
                  next;
              if (includeCurrent && !elem.previousElementSibling) {
                  parent = elem.parentNode;
                  text = parent.textContent;
                  while (parent.hasChildNodes()) {
                      parent.removeChild(parent.lastChild);
                  }
              } else {
                  elem = includeCurrent ? elem.previousElementSibling : elem;
                  while (next = elem.nextSibling) {
                      text += next.textContent;
                      elem.parentNode.removeChild(next);
                  }
              }
              return text;
          }
          
          function splitText(text, useRegex) {
              var chunks = [],
                  i, textSize, boundary = 0;
              if (useRegex) {
                  var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
                  chunks = text.match(regex) || [];
              } else {
                  for (i = 0, textSize = text.length; i < textSize; i = boundary) {
                      boundary = i + chunkSize;
                      if (boundary <= textSize && text.charAt(boundary) == ' ') {
                          chunks.push(text.substring(i, boundary));
                      } else {
                          while (boundary <= textSize && text.charAt(boundary) != ' ') {
                              boundary++;
                          }
                          chunks.push(text.substring(i, boundary));
                      }
                  }
              }
              return chunks;
          }
          #text_land {
              border: 1px solid #ccc;
              padding: 25px;
              margin-bottom: 30px;
          }
          
          textarea {
              width: 95%;
              height: 100px;
          }
          
          label {
              display: block;
              width: 50%;
              clear: both;
              margin: 0 0 .5em;
          }
          
          label select {
              width: 50%;
              float: right;
          }
          
          * {
              box-sizing: border-box;
              padding: 0;
              margin: 0;
          }
          
          body {
              font-family: monospace;
              font-size: 1em;
          }
          
          h3 {
              margin: 1.2em 0;
          }
          
          div {
              margin: 1.2em;
          }
          
          textarea {
              width: 100%;
          }
          
          button {
              padding: .5em;
          }
          
          p {
              padding: 1.2em .5em;
              margin: 1.4em 0;
              width: 200px;
              height: 200px;
              border: 1px dashed #aaa;
          }
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
          <div id="styles">
                  <label>Font-size: 
                  <select id="FontSize" data-property="font-size">
                      <option disabled>
                          Select font-size:
                      </option>
                      <option>
                          smaller
                      </option>
                      <option>
                          10px
                      </option>
                      <option>
                          12px
                      </option>
                      <option>
                          14px
                      </option>
                      <option>
                          16px
                      </option>
                      <option>
                          18px
                      </option>
                      <option>
                          20px
                      </option>
                      <option>
                          larger
                      </option>
                  </select></label>
              </div>
              <div>
                  <h3>Paste text in the field below to divide text into paragraphs..</h3>
                  <textarea id="textarea1" placeholder=
                  "Type text here, then press the button below." rows="5">
          </textarea><br>
                  <br>
                  <button id="go">Divide Text into Paragraphs</button>
              </div>
              <div>
                  <h3 align="right">Divided Text Will Appear Below:</h3>
                  <hr>
                  <div id="content"></div>
              </div>

          【讨论】:

          • 是否可以使用高度属性自动生成所有段落?
          • 我不明白你可以多解释一下!
          猜你喜欢
          • 1970-01-01
          • 2023-04-07
          • 2017-07-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-08
          相关资源
          最近更新 更多