Как динамически изменить цвет и размер текста всех абзацев при щелчке внутри ‹div›?

Следующая скрипта позволяет вставлять текст в <textarea> и создавать абзацы при нажатии кнопки.

Возможно ли в приведенном ниже коде создать два раскрывающихся списка <select></select>, один из которых изменяет цвет абзацев <p> на любой цвет, который пользователь выбирает при щелчке, а другой — для динамического изменения размера текста?

Прилагается Fiddle. Было бы очень полезно, если бы скрипка могла быть обновлена, так как я все еще новичок в кодировании.

HTML:

<div>
<div id="text_land" style="border:1px solid #ccc; padding:25px; margin-bottom:30px;">xzxz</div>
<textarea style="width:95%;"></textarea>
<button>Go</button>

Javascript:

$(function () {
  $('button').on('click', function () {
    var theText = $('textarea').val();
    var i = 200;
    while (theText.length > 200) {
        console.log('looping');
        while (theText.charAt(i) !== '.') {
            i++;   
        }

        console.log(i);
        $("#text_land").append("<p>" + theText.substring(0, i+1) + "</p>");
        theText = theText.substring(i+1);
        i = 200;
    }

    $('#text_land').append("<p>" + theText + "</p>");
  })

})

Спасибо!


person Dave    schedule 08.11.2015    source источник


Ответы (3)


Хотя вы уже приняли ответ, я решил предложить небольшую альтернативу; который немного более лаконичен и, надеюсь, очевиден в отношении того, как расширить возможности для поддержки других свойств css:

$(function() {
  
  // a slight change to your own approach,
  // binding an anonymous function as the
  // click event-handler of the <button>:
  $('button').on('click', function() {
    
    // getting the value of the <textarea>
    // element that follows the '#text_land'
    // element:
    var v = $('#text_land + textarea').val(),
        
        // splitting the value on double-
        // linebreaks to allow paragraphs to
        // be formed, and joining the array-
        // elements together with closing and
        // opening tags; then wrapping the
        // whole string in an opening and
        // closing tag:
      paragraphs = '<p>' + v.split(/\n\n/).join('</p><p>') + '</p>';
    
    // appending the paragraphs to the
    // '#text_land' element:
    $(paragraphs).appendTo('#text_land');
  });

  // binding an anonymous function as the
  // change event-handler for the <select>
  // elements:
  $('select').on('change', function() {
    
    // finding the elements that should
    // be affected:
    var targets = $('#text_land p'),
        
        // finding the CSS property to
        // update (held in the
        // 'data-property' attribute):
      property = this.dataset.property;

    // updating the CSS property of
    // those elements with the
    // property-value held in the 
    // <select> element's value property:
    targets.css(property, this.value);
    
    // because we're using disabled <option>
    // elements to act as the 'label' within
    // the <select> we set the selectedIndex
    // property to 0 (since those disabled
    // <label> elements are the first <option>
    // which shows the 'label' on page-load,
    // but the disabled attribute/property
    // prevents the user from re-selecting it):
  }).prop('selectedIndex', 0);
});
#text_land {
  border: 1px solid #ccc;
  padding: 25px;
  margin-bottom: 30px;
}
textarea {
  width: 95%;
}
label {
  display: block;
  width: 50%;
  clear: both;
  margin: 0 0 0.5em 0;
}
label select {
  width: 50%;
  float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div id="styles">
    <!--
    wrapping the <select> elements in <label> elements, so that
    clicking the text will focus the <select>:
    -->
    <label>Color:
      <!--
      using a custom data-* attribute to store the css property
      that each <select> will affect/update:
      -->
      <select data-property="color">
        <!--
        Setting the first <option> to 'disabled' in order that
        the user cannot select the (pseudo) 'label' text:
        -->
        <option disabled>Select color:</option>
        <option>red</option>
        <option>green</option>
        <option>blue</option>
      </select>
    </label>
    <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>
    <label>Background-color:
      <select data-property="background-color">
        <option disabled>Select background-color:</option>
        <option>aqua</option>
        <option>fuchsia</option>
        <option>limegreen</option>
        <option>silver</option>
      </select>
    </label>
  </div>
  <div id="text_land">xzxz</div>
  <textarea></textarea>
  <button>Go</button>
</div>

демонстрация JS Fiddle.

Преимущество этого подхода заключается в том, что один обработчик событий может действовать как обработчик событий для всех элементов <select>, если соответствующие значения указаны в тегах <option>, а соответствующее свойство CSS содержится в атрибуте data-property элемента <select>. сам элемент. Это позволяет избежать необходимости писать обработчики событий для каждого отдельного элемента <select>, который обновляет другое значение свойства.

Использованная литература:

person David says reinstate Monica    schedule 08.11.2015
comment
Спасибо за обновленный код! Хотя оба предложения кода, включая приведенный ниже ответ, великолепны, я выберу этот ответ в качестве решения из-за возможности поддержки других свойств CSS. - person Dave; 08.11.2015
comment
Всегда пожалуйста, я рад, что помог; и спасибо за прием! :) - person David says reinstate Monica; 08.11.2015
comment
Кроме того, возможно ли с помощью этого нового кода указать, сколько символов содержится в каждом абзаце, как в оригинальной скрипке? Спасибо. - person Dave; 08.11.2015
comment
О, абсолютно; Я изменил это чисто для краткости. Вы можете легко заменить вставку абзаца из моего кода на свой собственный оригинал. - person David says reinstate Monica; 08.11.2015

Ниже приведен обновленный скрипт.

Код

$(function () {
    $('button').on('click', function () {
        var theText = $('textarea').val();
        var i = 200;
        while (theText.length > 200) {
            console.log('looping');
            while (theText.charAt(i) !== '.') {
                i++;   
            }
            
            console.log(i);
            $("#text_land").append("<p>" + theText.substring(0, i+1) + "</p>");
            theText = theText.substring(i+1);
            i = 200;
        }
        
        $('#text_land').append("<p>" + theText + "</p>");
    })
    
    $("#color").on("change", function(){
    	$("#text_land").css("color", $(this).val())
    });
    
    $("#size").on("change", function(){
    	$("#text_land").css("font-size", $(this).val());
    });
    
    $("#bgcolor").on("change", function(){
    	$("#text_land").css("background", $(this).val())
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
    <div id="text_land" style="border:1px solid #ccc; padding:25px; margin-bottom:30px;">xzxz</div>
    <textarea style="widht:95%;"></textarea>
    <button>Go</button>
</div>

<select id="color">
    <option>Color</option>
    <option>Red</option>
    <option>Blue</option>
    <option>Black</option>
    <option>Green</option>
</select>

<select id="bgcolor">
    <option>Background Color</option>
    <option>Red</option>
    <option>Blue</option>
    <option>Black</option>
    <option>Green</option>
</select>


<select id="size">
    <option>Size</option>
    <option>16px</option>
    <option>18px</option>
    <option>20px</option>
    <option>22px</option>
</select>

person Rajesh    schedule 08.11.2015
comment
Спасибо за обновленный код! Возможно ли иметь другой раскрывающийся список, который меняет цвет фона каждого раздела абзаца, а не пробелы между абзацами ‹p›? - person Dave; 08.11.2015
comment
Просто поместите текст в тег <p> вместо <div>, и все заработает. Также обновите идентификатор, чтобы он соответствовал одному в JS. - person Rajesh; 08.11.2015

  1. создавать классы css, например: .red, .blue и т. д.

    .красный {цвет: красный; }

  2. При изменении значения раскрывающегося списка выполните цикл по тегам <p> в блоке и добавьте требуемый класс к тегам <p> (<p class="red">).

Повторите то же самое для изменения размера шрифта, создав класс css требуемого размера шрифта.

person schoolcoder    schedule 08.11.2015