我想在单击按钮时使输入/文本区域文本变粗体/斜体。

huangapple go评论54阅读模式
英文:

I would like to make an input/textarea text bold/italic when i clicked on a button bold/italic

问题

我已经创建了一个文本区域,在这里我会写一些内容。然后我会点击一个按钮。文本将变成粗体。但它不起作用。以下是我的HTML和JS代码:

```HTML: 
<textarea cols="30" rows="10" id="textAreaText"></textarea>
<button id="btn-bold">粗体</button>
<button id="btn-italic">斜体</button>

JS: 
<script>
document.getElementById('btn-bold').addEventListener('click', function() {
    const textArea = document.getElementById('textAreaText');
    const textAreaValue = textArea.value;
    textArea.style.fontWeight = "bold";
    console.log(textAreaValue);
})
</script>
英文:

I have taken a textarea where i will write someting.Then I will click on a button.And the text will turn bold.But it is not working.Here is my html and js code

   HTML :  &lt;textarea cols=&quot;30&quot; rows=&quot;10&quot; id=&quot;textAreaText&quot;&gt;&lt;/textarea&gt;
      &lt;button id=&quot;btn-bold&quot;&gt;bold&lt;/button&gt;
      &lt;button id=&quot;btn-italic&quot;&gt;italic&lt;/button&gt;
  
  js:  &lt;script&gt;
 
document.getElementById(&#39;btn-bold&#39;).addEventListener(&#39;click&#39;,function (){
    const textArea=document.getElementById(&#39;textAreaText&#39;);
    const textAreaValue=textArea.value;
    textAreaValue.style.fontWeight=&quot;bold&quot;;
    console.log(textAreaValue);

})
&lt;/script&gt;```

</details>


# 答案1
**得分**: 1

你正在尝试为一个字符串添加样式。

在这里,常量 `textAreaValue` 包含的字符串与 DOM 元素无关,

要使其加粗,请删除以下行:

```javascript
const textAreaValue= textArea.value;

而是应该修改你的 JavaScript 代码如下:

const textArea=document.getElementById('textAreaText');
textArea.style.fontWeight = "bold";
英文:

You're trying to style a string

right here the constant textAreaValue is holding a string that is not related to the DOM element,

to make it bold remove this line

        const textAreaValue= textArea.value;

instead your javascript should look like this

    const textArea=document.getElementById(&#39;textAreaText&#39;);
    textArea.style.fontWeight = &quot;bold&quot;;

答案2

得分: 0

使文字变为 斜体

document.getElementById('textAreaText').style['font-style'] = 'italic';

使文字变为 粗体

document.getElementById('textAreaText').style['font-weight'] = 'bold';
英文:

To make it italic :

document.getElementById(&#39;textAreaText&#39;).style[&quot;font-style&quot;]=&quot;italic&quot;

To make it bold :

document.getElementById(&#39;textAreaText&#39;).style[&quot;font-weight&quot;]=&quot;bold&quot;

huangapple
  • 本文由 发表于 2023年2月26日 23:43:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定