【问题标题】:Change Font of Text Area as Per DropdownList Selection根据下拉列表选择更改文本区域的字体
【发布时间】:2019-08-22 10:24:57
【问题描述】:

我的 html 文件中有一个下拉列表和一个文本区域,代码如下

<select id='ddlViewBy' name='ddlViewBy' onchange='applyfonttotextarea()'>
<option value = '1'>Arial</option>
<option value = '2' selected = 'selected'>Comic Sans</option>
<option value ='3'>Courier New</option>
</select>"

现在在上面的代码中,我在下拉列表中添加了一个 onchange 方法作为 applyfonttotextarea() 在这种方法中,我需要在 javascript 中编写一个逻辑来在文本区域中应用选定的字体样式。 如何编写该函数。

例如。在 textarea 中,我输入了“Hello Friends. How are You?”,我在其中选择了“Hello”一词并从下拉列表中选择 Courier New 选项,textarea 的“Hello”应该是 Courier New 字体。任何建议?

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    一个简单的解决方案是为您的&lt;select&gt; 元素实现一个change 事件处理程序,其中:

    1. 标识该&lt;select&gt; 的新选择选项
    2. 阅读所选选项的文本
    3. 将该文本作为活动字体系列应用到您要更新的&lt;textarea&gt;

    在代码中可以这样实现:

    document.getElementById('ddlViewBy').addEventListener('change', function(event) {
      
      /* Get select element of change event */
      const selectElement = event.currentTarget;
      
      /* Get selected option (step 1) */
      const selectedOption = selectElement.options[selectElement.selectedIndex];
      
      /* Get font family name from selected option's text (step 2) */
      const fontFamily = selectedOption.text;
      
      /* Get text area, and update it's fontFamily style (step 3) */
      document.getElementById('myTextarea').style.fontFamily = fontFamily;
      
    });
    <select id='ddlViewBy' name='ddlViewBy'>
      <option value='1'>Arial</option>
      <option value='2' selected='selected'>Comic Sans</option>
      <option value='3'>Courier New</option>
    </select>
    <br/>
    <textarea id="myTextarea">some text</textarea>

    另请注意,这种方法意味着不再需要 onchange='applyfonttotextarea()' 的内联绑定。

    希望有帮助!

    【讨论】:

    • 非常感谢 Dacre。这有帮助。但正如我提到的,当我们更改下拉列表时,只有选定的文本应该被更改。这里正在更改整个文本。有什么想法吗?
    • 抱歉,错过了那个细节(正在阅读选择作为选择的选项,但没有注意到每个单词选择的提及)。不幸的是,这是不可能的,但它可以通过内容编辑来实现:developer.mozilla.org/en-US/docs/Web/Guide/HTML/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多