1.做一个编辑框,里面可以选择字体的颜色、字形、样式,代码如下:
<!DOCTYPE html>
<html><head>
<title>学习javascript代码</title>
</head>
<body>
<fieldset>
<legend>编辑区</legend>
<div>
<form>
字体颜色:
<select οnchange="setFontColor(this)">
<option value="black">Dlack </option>
<option value="red">Red </option>
<option value="green">Green </option>
<option value="blue">Blue </option>
</select>
字体样式:
<select οnchange="setFontStyle(this)">
<option value="bold">Bold </option>
<option value="italic">Italic </option>
<option value="underline">Underline </option>
<option value="comic sans ms">Comic Sans</option>
</select>
字体:
<select οnchange="setFontFamily(this)">
<option value="serif">Serif </option>
<option value="sans-serif">Sans-serif</option>
<option value="monospace">Mono</option>
<option value="comic sans ms">Comic Sans</option>
</select>
</form>
</div>
<br>
<div id="editableText" contenteditable="true"
style="width:400;min-height:100px;border:2px #ccc dashed;">
</div>
</fieldset>
<script type="text/javascript">
function setFontColor(choice){
document.execCommand("forecolor",false,choice,value);
}
function setFontStyle(choice){
document.execCommand(choice,value,false,null);
}
function setFontFamily(choice){
document.execCommand("fontname",false,choice,value);
}
</script>
</body>
</html>
2.笔记:
document.getElementById('box').scrollIntoView(); //使box标签标记的位置始终处于可见位置,这里是每刷新就会让指定位置可见
var box=document.getElementById('box');
box.children.length; //忽略空白节点
box.children[0].nodeName; //获取第一个节点
例题:实现跨浏览器判断一个节点是否是另一节点的字节点(可是兼容更低版本的)
window.οnlοad=function(){
var box=document.getElementById('box');
var p=box.firstChild;
//alert(box.contains(p));
alert(contain(box,p));
}
function contain(reNode,otherNode){
if(typeof reNode.contains !='undefined'){
return reNode.contains(otherNode);
}
else if(typeof reNode.compareDocumentPosition==='function'){
return !!(reNode.compareDocumentPosition(otherNode)>16);
}
else{
var node=otherNode.parentNode;
do{
if(node===reNode)
return true;
else{
node=node.parentNode;
}
}while(node!=null);
}
return false;
}
例题:跨浏览器获取文本内容,兼容各大浏览器
window.οnlοad=function(){
var box=document.getElementById('box');
alert(mytext(box));
}
function mytext(node){
if(typeof node.textContent=='string')
return node.textContent;
else
return node.innerText;
}