我正在尝试在一个允许用户为学校项目编写自己的笔记的网页上工作,我的想法是让他们使用按钮将文本加粗/斜体化/下划线。截至目前,这些按钮可以正常工作,但它们会将文本区域内的所有内容加粗/斜体/加下划线。相反,我希望它以这样一种方式工作,即只有他们突出显示的文本才会变为粗体/斜体/下划线。我还想知道如何做到这一点,当他们单击粗体按钮时,他们从那时起输入的文本将显示为粗体,当他们再次单击它时,从那时起输入的文本将显示出来普通的。
<script type="text/javascript">
function boldText(){
var target = document.getElementById("TextArea");
if( target.style.fontWeight == "bolder" ) {
target.style.fontWeight = "normal";
} else {
target.style.fontWeight = "bolder";
}
}
function italicText(){
var target = document.getElementById("TextArea");
if( target.style.fontStyle == "italic" ) {
target.style.fontStyle = "normal";
} else {
target.style.fontStyle = "italic";
}
}
function underlineText(){
var target = document.getElementById("TextArea");
if( target.style.textDecoration == "underline" ) {
target.style.textDecoration = "none";
} else {
target.style.textDecoration = "underline";
}
}
</script>
原文由 cosmo 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用
execCommand()
。该 API 用于开发文本编辑器。这 3 个按钮使用了非常通用的execCommand()
并且书写元素是一个普通的 div,启用了属性contenteditable
。片断