繁体   English   中英

如何仅将“选定”文本更改为“使用 html 和 JavaScript”输入标签中存在的“粗体/非粗体”

[英]How to change the “selected” text to “bold / unbold” which is present in input tag “using html and JavaScript” only

我正在尝试 select 输入标签中的文本/字符,当我按下粗体按钮时,选定的文本应变为粗体,再次按下按钮时,选定的文本应变为正常。

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

<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>

我认为: function 返回一个字符串,它不是文档中的元素并且没有样式属性

我认为这就是你想要做的。

 <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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM