Подтвердить что ты не робот

Изменить размер шрифта динамически на определенные элементы абзаца <p>?

Следующий JSFiddle разбивает тексты на отдельные абзацы <p> с заданным текстовым пределом.


Можно ли изменить размер текста в полях в соответствии с параметром выбора с помощью contenteditable, сохраняя возможность редактировать, удаляя текстовое ограничение и сохраняя свойство динамического размера?

ОБНОВЛЕНИЕ 2: Все созданные поля должны быть:

"равны одинаковой высоте и ширине

и измените, когда шрифт обновляется динамически, необходимо быть согласованным во всех элементах.


ОБНОВЛЕНИЕ 3: Последний сгенерированный абзац не равен другим абзацам с высотой размера границы.


ОБНОВЛЕНИЕ 4: Все абзацы должны быть сгенерированы одинаково с атрибутом height auto. Проблема с текущими ответами заключается в том, что последняя сформированная граница абзаца также должна быть равна той же высоте, что и предыдущая граница высоты, как и другие абзацы, в том числе при изменении размера шрифта.

Обновление 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>
4b9b3361

Ответ 1

Я не уверен, что я понимаю проблему... Вы можете установить размер шрифта в родительский элемент (#content {font-size: whatever}) и наследовать его (#content p {font-size: inherit}). Если вы установите размер шрифта в родительском, если применитесь к уже добавленным абзацам И новым, когда вы их добавите.

(Изменения в скрипте: Селектор в изменении выбора, CSS-селекторов/свойств для "p" и "#content p" )

(Ответ отредактирован для абзацев одинаковой высоты) Чтобы получить такую ​​же высоту, я добавил функцию sameheight (селектор). Я не уверен, когда вы хотите вызвать его, я надел его на выбранное изменение и изменение (текст). (Надеюсь, что это поможет. Исправлена ​​высота в функции с использованием externalHeight) ... и скрипка снова отредактирована: 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 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>

Ответ 2

Здесь вы идете JSFiddle

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

Ответ 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/

Ответ 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

Ответ 8

Я создал вилку вашей скрипки и отредактировал (добавил) обработчик события 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>