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