日期:2014-05-16  浏览次数:20322 次

关于定义几个加粗、斜体、下划线和居中功能的按钮
下面一段JS程序,运行后点击相应的按钮却没有反应,不知道问题出在哪,fontchuli该怎么修改?
JScript code

function fontchuli()
{
    document.news.content.focus();
    var re = document.selection.createRange();
    if (document.news.content.createTextRange)
    {
       re.text = fontbegin + re.text + fontend;
    }
    else
    {
       document.news.content.value= fontbegin+document.news.content.value+fontend;
    }
}
//定义加粗文字函数
function cbold()
{
    fontbegin="[b]";
    fontend="[/b]";
    fontchuli();
}
//定义斜体文字函数
function italic()
{
    fontbegin="[em]";
    fontend="[/em]";
    fontchuli();
}
//定义居中显示函数
function middle()
{
    fontbegin="[center]";
    fontend="[/center]";
    fontchuli();
}
//定义下划线函数
function underline()
{
    fontbegin="[u]";
    fontend="[/u]";
    fontchuli();
}


------解决方案--------------------
<script type="text/javascript">
var fontbegin="";
var fontend="";
function se(){
var a="";
var text=document.getElementById("test").innerHTML;
if(window.getSelection){
a=window.getSelection();
}else if(document.getSelection){
a.document.getSelection();
}else if(document.selection){
a=document.selection.createRange().text;
}
var b=text.indexOf(a);
var before=text.substring(0,b);
var after=text.substring(b+a.length);
a=fontbegin+a+fontend;
document.getElementById("test").innerHTML=before+a+after;
}
function cbold(){
fontbegin="<b>";
fontend="</b>";
se();
}
function italic(){
fontbegin="<em>";
fontend="</em>";
se();
}
function middle(){
fontbegin="<center>";
fontend="</center>";
se();
}
function underline(){
fontbegin="<u>";
fontend="</u>";
se();
}
</script>
</head>

<body>
<div id="test">this is just a test</div>
<input type="button" value="cb" onclick="cbold()">
<input type="button" value="it" onclick="italic()">
<input type="button" value="mi" onclick="middle()">
<input type="button" value="un" onclick="underline()">
</body>
</html>
这样试试
------解决方案--------------------


//字體變粗 

document.execCommand('Bold'); 

//變斜體 

document.execCommand('Italic'); 

//將選中的文字加下劃線 

document.execCommand('Underline');