简体   繁体   English

在特定段落<p>元素上动态更改字体大小?

[英]Change font size dynamically on specific paragraph <p> elements?

The following JSFiddle splits texts into individual paragraph <p> boxes with a set text limit. 以下JSFiddle将文本拆分为具有设置文本限制的单个段落<p>框。


Is it possible to change the text size in the boxes according to the select option through contenteditable while still allowing to edit, removing the text limit and remaining the dynamic size property? 是否可以根据select选项通过contenteditable更改框中的文本大小,同时仍然允许编辑,删除文本限制和保留动态大小属性?

UPDATE 2: The boxes generated all need to be: 更新2:生成的框都需要:

"equal the same height and width" “相同的高度和宽度”

and change when the font is updated dynamically, needing to be consistent across all elements. 并在字体动态更新时更改,需要在所有元素中保持一致。


UPDATE 3: The last generated paragraph is not equal to the other paragraphs with border size height. 更新3:最后生成的段落不等于边框大小高度的其他段落。


UPDATE 4: All paragraphs need to be generated equally with the height attribute auto. 更新4:所有段落都需要与height属性auto一样生成。 The problem with the current answers is the that the last generated paragraph border also needs to equal the same height as the previous height border as the other paragraphs, including when changing the font size. 当前答案的问题在于,最后生成的段落边界也需要与前一个高度边界相同的高度与其他段落相同,包括更改字体大小时。

Update 5 [image]: Example of Problem with last divided paragraph height and border not equal to others. 更新5 [图像]:上一个分段高度和边框不等于其他的问题示例。

上一个分段高度不等于其他的问题示例。

Link to Fiddle 链接到小提琴

If a new fiddle could be provided, it would be very much appreciated, as I am still new to coding. 如果可以提供一个新的小提琴,我将非常感激,因为我还是新编码。 Thank You! 谢谢!

 $(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> 

Here you go JSFiddle 在这里你去JSFiddle

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

Try like this 试试这样吧

 <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> 

I believe i have the answer for you: 我相信我有你的答案:

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

I changed the function in order to set the font-size to the div rather that the paragraph. 我更改了函数,以便将font-size设置为div而不是段落。 Is this what you wanted? 这是你想要的吗? As it is what i gathered from the info provided. 因为这是我从提供的信息中收集的。

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

I'm not sure if I'm understanding the problem... You can set the font size to the parent element (#content{font-size:whatever}) and inherit it (#content p {font-size:inherit} ). 我不确定我是否理解了这个问题...您可以将字体大小设置为父元素(#content {font-size:whatever})并继承它(#content p {font-size:inherit} )。 If you set the font size in the parent if will apply to the the already added paragraphs AND the new ones when you add them. 如果在父项中设置字体大小,则在添加它们时将应用于已添加的段落和新的段落。

(Changes in the fiddle: Selector in the change of the select, CSS selectors/properties for "p" and "#content p") (小提琴中的变化:选择更改中的选择器,“p”和“#content p”的CSS选择器/属性)

(Answer edited for "same height" paragraphs) To get same height I added a sameheight(selector) function. (针对“相同高度”段落编辑的答案)为了获得相同的高度,我添加了相同的高度(选择器)功能。 I'm unsure about when you would like to trigger it, I've put it on select change and rearange(text). 我不确定你什么时候想触发它,我把它放在选择更改并重新排列(文本)。 (Hope it helps. Fixed the height in function using outerHeight) ...and fiddle edited again: sameheight is also fired on window resize events. (希望它有所帮助。使用outerHeight修复了函数中的高度)...再次编辑小提琴:同样高度也会在窗口调整大小事件上被触发。

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> 

You can inject a dynamic style element into the DOM and update it with the font size you're after. 您可以将动态style元素注入DOM,并使用您所使用的字体大小进行更新。 You could use an MV* framework to update its content. 您可以使用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>');
});

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

这应该有所帮助:

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

To change of font size of the div and text area: 要更改div和文本区域的字体大小:

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

to keep the height of your text area: in CSS 保持文本区域的高度:在CSS中

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

use px aslo instead em 使用px aslo而不是em

I have created a fork of your fiddle and have edited(added) the event handler of select. 我创建了一个小提琴的分支,并编辑(添加)了select的事件处理程序。 I have added some code in their which maintains the font-size of editable p elements. 我在其中添加了一些代码,用于维护可编辑p元素的字体大小。 Using that reference you can then apply all your styles as per your requirement. 使用该引用,您可以根据您的要求应用所有样式。

Don't forget to mark it right and upvote if you find my answer right. 如果您的答案正确,请不要忘记将其标记为正确并进行投票。

JS Fiddle Fork 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>');

Try this 试试这个

 $('#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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM