我试图从一个输入标签中选择一个文本字符,当我按下一个粗体按钮时,选中的文本应该变为粗体,当再次按下按钮时,选中的文本应该变为正常。
这是我的代码,但它不工作。
<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>
我认为:函数返回的是一个字符串,它不是文档中的元素,也没有样式属性。
我想这就是你要做的事情。
<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>