题目:
设计一款文字编辑器,可以简单实现字体的转换,字号的变换,加粗、倾斜、下划线,可以更改字体的颜色。
大致如下图:
1.以下两行代码,为完成此次文本编辑器的核心代码功能;
document.execCommand()
document.execCommand(sCommand[,交互方1式, 动态参数])
在设置字体的加粗,倾斜,下划线时,在对应的按钮上设置click事件为:
document.execCommand(‘Bold’)——加粗
document.execCommand(‘Italic’)——倾斜
document.execCommand(‘Underline’)——下划线
在对应的select中的添加了onchange:
例如:onchange = document.execCommand(‘FontSize’,false,this.value)
此时就相当于鼠标在select元素上进行了选择,当鼠标选择的某一元素时(假设,此时鼠标选择了3号字体),就模仿出了select的onchange效果,此时在文本域中编辑时,对应的字号就是鼠标单击是选择的字号。
源代码:
<!DOCTYPE html>
<html>
<head>
<title>Edit</title>
<meta charset="utf-8">
<style type="text/css">
#myspan
{
color: #bbb;
position: absolute;
left: 300px;
top: 10px;
}
#mydiv
{
background-color: pink;
width: 330px;
position: absolute;
left: 200px;
top: 40px;
}
#mytext
{
border: 2px solid pink;
width: 400px;
height: 300px;
position: absolute;
left: 165px;
top: 70px;
}
</style>
</head>
<body>
<form id="myform" method="post">
<span id="myspan">简易文本编辑器</span>
<div id="mydiv">
<select id="fontfamily" onchange=document.execCommand('FontName',false,this.value)>
<option id="宋体">
宋体
</option>
<option id="微软雅黑">
微软雅黑
</option>
<option id="方正姚体">
方正姚体
</option>
</select>
<select id="fontsize" onchange=document.execCommand('FontSize',false,this.value)>
<option id="3号">
3号
</option>
<option id="5号">
5号
</option>
<option id="7号">
7号
</option>
</select>
<button type="button" onclick=document.execCommand('Bold')>B</button>
<button type="button" onclick=document.execCommand('Italic')>I</button>
<button type="button" onclick=document.execCommand('Underline')>U</button>
<select id="fontcolor" onchange=document.execCommand('ForeColor',false,this.value)>
<option id="red">
red
</option>
<option id="blue">
blue
</option>
<option id="yellow">
yellow
</option>
</select>
</div>
<div id="mytext"contenteditable ></div>
</form>
</body>
</html>
下面这部分代码为css样式,添加此部分至head标签内部,可以根据自己的实际需要更改样式;
其中,运用到了position,它主要作用为将你所需要的元素放置合适的位置,起定位的作用;
position:absolute;绝对定位,有四个属性:left,right,top,bottom;
当使用时,必须至少使用一个才能激活absolute;
<style type="text/css">
#myspan
{
color: #bbb;
position: absolute;
left: 300px;
top: 10px;
}
#mydiv
{
background-color: pink;
width: 330px;
position: absolute;
left: 200px;
top: 40px;
}
#mytext
{
border: 2px solid pink;
width: 400px;
height: 300px;
position: absolute;
left: 165px;
top: 70px;
}
</style>
期待您的意见,不妥之处请见谅!