DOM的常用属性
- document.body:body元素
- document.title:获取、设置文档的标题
- document.head:获取head标签
- document.styleSheets:获取css样式对象
- document.URL:获得完整的URL
- document.domain:获取域名
console.log(document.body);//body标签
console.log(document.title);//title标签
console.log(document.head);//head标签
console.log(document.styleSheets);//css样式对象
console.log(document.URL);//当前地址
console.log(document.domain);//当前域
DOM操作节点的属性
- getAttribute(属性):获取节点上的属性
- setAttribute(属性,值):给节点创建一个新属性
- removeAttribute(name):删除节点上的属性
自定标签属性时,1、命名单词之间使用-连接,2、标签属性值必须是字符串
var div=document.querySelector("div");
//获取标签属性 属性值都是字符串
div.getAttribute("name");
//自定标签属性时,1、命名单词之间使用-连接,2、标签属性值必须是字符串
div.setAttribute("toggle-data","30");
//删除标签属性
div.removeAttribute("toggle-data");
案例:实现浏览器标题文字滚动的效果:
var str="静下心来,沉淀自己,你会越来越棒";
var n=-1;
setInterval(animation,100);
function animation(){
n++;
if(n>str.length-1) n=0;
document.title=str.slice(n);
}
DOM对象的样式
行内样式通过dom.style…来获取和设置,不能获取CSS中的样式
需要注意,如果样式属性中有 ”-“ 连接符,需要将连接符省略,后面的第一个字母用大写。
var div=document.getElementById("div");
//设置行内样式
div.style.backgorundColor="red";
// 获取行内样式,不能获取CSS样式
console.log(div.style.backgroundColor)
计算后样式,即CSS样式和行内样式合并计算后的样式,
- 非IE所支持的获取非行间样式的方法:
用法:getComputedStyle(对象,伪类).样式名
例:getComputedStyle(oDiv,null).color - IE所支持的获取非行间样式的方法
用法:对象.currentStyle.样式名
例:oDiv.currentStyle.width
var div=document.getElementById("div");
//仅适用于IE浏览器
console.log(div.currentStyle.width)
//IE8以下不支持,谷歌火狐支持
console.log(getComputedStyle(div).width);
//可以合并写为
var style=getComputedStyle(div) || div.currentStyle;
设置CSS样式不可用:
document.styleSheets[0].disabled=true;
给css中添加一条样式规则:
insertRule(),第一个参数样式字符串,第二个参数是要插入位置的下标
//创建style标签
var style=document.createElement("style");
//将style标签插入到head里面
document.head.appendChild(style);
//给style里面添加一条样式规则
document.styleSheets[1].insertRule("div {width:100px;height:100px;background-color:blue;border: 1px solid #000000 }",0);
console.log(document.styleSheets);
扩展案例:insertRule()的实现过程
var obj={
width:"50px",
height:"50px",
backgroundColor:"red",
border:"1px solid #000000"
}
insertCss("div",obj);
insertCss("div:hover",{
width:"100px",
height:"100px",
borderTop:"1px solid #000000",
borderBottom:"1px solid #000000",
fontSize:"25px"
});
function insertCss(elem, data) {
//如果当前页面中没有css样式对象的话,创建一个插入到head中
if (document.styleSheets.length === 0) {
var _style=document.createElement("style");
document.head.appendChild(_style);
}
//获取最后一个css样式
_style = document.styleSheets[document.styleSheets.length-1];
var str=elem+" {";
for (var prep in data) {
//替换字符中的大写属性,如borderColor替换为border-color
str+=prep.replace(/([A-Z])/g,function(item){
return "-"+item.toLowerCase();
})+":"+data[prep]+";"
}
str += "}";
//将拼接好的字符插入到css样式对象中
_style.insertRule(str,_style.cssRules.length);
}