【问题标题】:Change Width and Height of Element Dynamically?动态改变元素的宽度和高度?
【发布时间】:2016-03-24 09:11:30
【问题描述】:

是否有可能通过以下小提琴,使用带有<button><input> 元素来动态控制所有段落<p> 元素的宽度和高度以应用更改?

下面的小提琴将文本转换成等分的段落,因此,当改变分割段落的宽度和大小时,段落都需要包含相同数量的字符。

但是,段落的预设大小应该已经应用并且可以通过使用输入元素为用户自定义。

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

谢谢!

更新一:调整宽高时,文字填充时需要自动流入下一段。那么,是否可以改变chunkSize元素在改变宽高时自动覆盖字符限制呢?

Fiddle

$(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;
}
#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">
  <h5>Size:</h5>
  <br>
  <label>Height:</label>
  <input>
  <br>
  <label>Width:</label>
  <input>
  <br>
  <button>
    Change Size
  </button>
</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】:

    要动态调整元素的大小,您可以使用以下代码(例如):

    $(window).resize(function(){
       var newwidth = "10px";
       var newheight = "10px";      
       $("#content p").css({"height": newheight, "width": newwidth });
    });
    

    只需将变量newwidthnewheight 设置为用户输入的新值。

    【讨论】:

      【解决方案2】:

      只是在最后添加了一个小功能, 并为输入字段提供一个 ID 按钮。

      https://jsfiddle.net/sa2L4fas/2/

      $(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;
      }
      
      $("#changeSize").click(function() {
        $("#content p").css({
          "width": $("#width").val(),
          "height": $("#height").val()
        });
      })
      #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">
        <h5>Size:</h5>
        <br>
        <label>Height:</label>
        <input id="height">
        <br>
        <label>Width:</label>
        <input id="width">
        <br>
        <button id="changeSize">
          Change Size
        </button>
      </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
      • 1970-01-01
      • 2012-06-19
      • 2012-01-16
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      相关资源
      最近更新 更多