如何将输入标签 "使用html和JavaScript "中的 "选中 "文字改为 "粗体不粗体"?

问题描述 投票:0回答:2

我试图从一个输入标签中选择一个文本字符,当我按下一个粗体按钮时,选中的文本应该变为粗体,当再次按下按钮时,选中的文本应该变为正常。

这是我的代码,但它不工作。

<body>
<input type="text" name=inp id="inp">

<button onclick="getSelectedText();"><b>B</b></button>


<script>
    document.getElementsByTagName('input').mouseup(function(){
    getSelectedText().style.fontWeight="bold";
});

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection().toString();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}
</script>

javascript html css frontend web-deployment
2个回答
0
投票

我认为:函数返回的是一个字符串,它不是文档中的元素,也没有样式属性。


0
投票

我想这就是你要做的事情。

<input type="text" name=inp id="inp">

<button onclick="bold()"><b>B</b></button>

<script>
  function bold() {
    var inp = document.getElementById('inp');
    inp.style.fontWeight = inp.style.fontWeight == 'bold' ? 'normal' : 'bold';
  }
</script>
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.