我正在尝试在允许用户为学校项目编写自己的笔记的网页上工作,我的想法是让他们使用按钮粗体/斜体/突出显示他们的文本.截至目前,按钮正在工作,但它们粗体/斜体/突出显示文本区域内的所有内容.相反,我希望它以这样的方式工作,即只有它们突出显示的文本才会变为粗体/斜体/下划线.
我也想知道如何制作它,以便当他们点击粗体按钮时,他们从那时开始输入的文字将变为粗体,当他们再次点击它时,从那时开始输入的文本将会出现正常.
<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>
解决方法:
您可以使用execCommand()
.此API用于开发文本编辑器. 3个按钮使用非常通用的execCommand(),而写入元素是使用属性contenteditable
启用的普通div.
SNIPPET
<!DOCTYPE html>
<html>
<head>
<Meta charset='utf-8'>
<style>
body {
font: 400 16px/1.4 'serif';
}
#editor1 {
border: 3px inset grey;
height: 100px;
width: 381px;
margin: 10px auto 0;
}
fieldset {
margin: 2px auto 15px;
width: 358px;
}
button {
width: 5ex;
text-align: center;
padding: 1px 3px;
}
</style>
</head>
<body>
<div id="editor1" contenteditable="true">
The quick brown fox jumped over the lazy dog.
</div>
<fieldset>
<button class="fontStyle" onclick="document.execCommand('italic',false,null);" title="Italicize Highlighted Text"><i>I</i>
</button>
<button class="fontStyle" onclick="document.execCommand( 'bold',false,null);" title="Bold Highlighted Text"><b>B</b>
</button>
<button class="fontStyle" onclick="document.execCommand( 'underline',false,null);"><u>U</u>
</button>
</fieldset>