gpt4 book ai didi

javascript - 根据下拉列表选择更改文本区域的字体

转载 作者:行者123 更新时间:2023-11-30 19:19:50 25 4
gpt4 key购买 nike

我的 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 中编写一个逻辑来在文本区域中应用选定的字体样式。如何编写该函数。

例如。在文本区域中,我输入了“Hello Friends。你好吗?”,我在其中选择了“Hello”字样,并从下拉列表中选择了 Courier New 选项,文本区域的“Hello”应该是 Courier New 字体。有什么建议吗?

最佳答案

一个简单的解决方案是实现 change您的 <select> 的事件处理程序元素在哪里:

  1. 确定新选择的选项 <select>
  2. 阅读所选选项的文本
  3. 将该文本作为事件字体系列应用于 <textarea>你想更新

在代码中,这可以实现为:

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()' 的内联绑定(bind)不再需要。

希望对您有所帮助!

关于javascript - 根据下拉列表选择更改文本区域的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57601237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com