[英]How to change the “selected” text to “bold / unbold” which is present in input tag “using html and JavaScript” only
I am trying to select a text/character from an input tag and when i press a bold button, selected text should change to bold and when the button is pressed again the selected text should change to normal.我正在尝试 select 输入标签中的文本/字符,当我按下粗体按钮时,选定的文本应变为粗体,再次按下按钮时,选定的文本应变为正常。
here is my code but its not working.这是我的代码,但它不起作用。
<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>
i think: the function returns a string, it is not an element in the document and has no style attribute我认为: function 返回一个字符串,它不是文档中的元素并且没有样式属性
I think this is what you are trying to do.我认为这就是你想要做的。
<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.