document.write()
-
语法:document.write(message)-- 数值-- 文字---标签
-
作用:在页面写入内容(操作的是body标签)
-
可以识别标签
document.write('你好'); document.write('<h1>你好h1标签</h1>'); document.write(1111);
JavaScript 元素操作
元素操作可以分为:内容操作,属性操作,样式的操作等
每种操作都分为读(获取)和写(设置)的操作
内容操作
1. 双标签元素的内容操作
双标签元素的内容操作 1.innerHTML 覆盖原来的内容 会识别标签 读:元素.innerHtml; 写:元素.innerHTML=值; 2.innerText 覆盖原来的内容 不会识别标签 读: 元素.innerText; 写: 元素.innerText=值; innerText和innerHTML的区别 1. innerText和innerHTML都会覆盖原来的内容 2.innerHTML会识别标签 3.innerText不会识别标签
// 1.获取div的内容 console.log(div.innerHTML); console.log(div.innerText); console.log(h1.innerHTML); // 设置内容 元素.innerHTML // 会覆盖原来的内容 h2.innerHTML = ''; h2.innerHTML = ''; btn.innerHTML = ''; p.innerText = ''; // 设置标签内容 // innerHTML可以识别标签 h2.innerHTML = '<i>斜体标签</i>'; // innerText 不可以识别标签,标签会作为内容输出 h3.innerText = '<i>斜体标签</i>';
2. 样式操作
-
样式(操作的行间样式)
width height background ....
-
语法
样式操作 设置:元素.style.样式名=值; 获取: 元素.style.样式名 注意:只能获取行间的样式 在js中不允许出现background - color这种连字符的属性,都需要使用驼峰标识来替代 样式中有-的,要转成驼峰 例如:background - color --- backgroundColor font-size ---- fontSize
// 获取样式 // 获取元素的字体颜色 console.log(div.style.color); //空,获取不到,因为只能获取行间样式 // 获取宽度 console.log(div.style.width); //200px console.log(div.style.height); //250px // 背景颜色 // console.log(div.style.background - color); //color is not defined // js中获取样式的时候不允许出现连字符-,需要转为小驼峰 // background - color : backgroundColor console.log(div.style.backgroundColor); //brown // 获取字体大小 font-size fontSize console.log(div.style.fontSize); //30px // 设置样式 div.style.backgroundColor = 'teal'; div.style.backgroundColor = '#ff0'; div.style.backgroundColor = 'rgba(100,100,100,.8)'; div.style.width = '300px'; div.style.height = '300px';