一、Style对象
语法:HTML元素.style.样式属性="值"
注意:遵循驼峰式写法
1、style对象的属性
类别 | 属性 | 描述 |
Padding (边距) | padding | 设置元素的填充 |
paddingTop paddingBottom paddingLeft paddingRight | 设置元素的上、下、左、右填充 | |
Border (边框) | border | 设置四个边框所有的属性 |
borderTop borderBtttom borderLeft borderRight | 设置上、下、左、右边框的属性 |
2、使用style属性改变样式
(1)className属性
语法:HTML元素.className="类名"
<ul>
<li onmouseover="this.className='over'" onmouseout="this.className='out'">例子1</li>
<li onmouseover="this.className='over'" onmouseout="this.className='out'">例子2</li>
<li onmouseover="this.className='over'" onmouseout="this.className='out'">例子3</li>
</ul>
(2)使用函数改变菜单效果
var len=document.getElementsByTagName("li");
for(var i=0;i<len.length;i++){
len[i].onmouseover=function(){
this.className="over";
}
len[i].onmouseout=function(){
this.className="out";
}
}
3、获取样式属性值
(1)获取行内样式的方法
document.getElementById(elementId).样式.属性名
var divObj=document.getElementById("test");
var objTop=divObj.style.top;
(2)获取类样式的方法
getComputedStyle() //全局方法
currentStyle //ie专有的方法
var divObj=document.getElementById("test");
var objTop= divObj.currentStyle.top;
var objTop =document.defaultView.getComputedStyle(divObj,null).top;
4、网页卷去的距离与偏移量
scrollLeft:设置或获取位于给定对象左边界与窗口中目前可见内容的最左端之 间的距离 ,即左边灰色的内容。
scrollTop:设置或获取位于对象最顶端与窗口中可见内容的最顶端之间的距离 , 即上边灰色的内容。
offsetLeft:获取指定对象相对于版面或由 offsetParent 属性指定的父坐标的计 算左侧位置 offsetTop:获取指定对象相对于版面或由 offsetParent 属性指定的父坐标的计 算顶端位置
注意:
- 区分大小写
- offsetParent:布局中设置position属性(Relative、Absolute、fixed)的父容器,从最近的父节点开始,一层层向上找,直到HTML的body。
- dom对象.classList.add(类名1,类名2.....)添加类
<script>
var oDiv = document.querySelector(".box"); var b = document.getElementById("btn");
oDiv.onscroll = function () {
//console.log(oDiv.scrollTop);//垂直方向滚动条滚动方向
//console.log(oDiv.scrollLeft);//水平方向滚动条滚动方向
}
b.onclick = function () {
// oDiv.scrollBy(0, 40);//oDiv.scrollTop=40;
//oDiv.scrollTo(0, 40);//oDiv.scrollTop+=40;
console.log(oDiv.scrollHeight);//div内容实际高度
console.log(oDiv.scrollWidth);//div内容实际宽度
}
</script>
二、新增内容
1、操作元素类样式 2)classList属性 元素classList属性可以获取元素的所有类---类数组。
方法:
- add(类名1,类名2,....):标在原有类基础上追加新类。
- remove(类名1,类名2,....):删除指定的类。
- toggle(类名):切换,如果有指定类名的类就删除,否则就添加。
- contains(类名):判断元素classList中是否包含指定类。含有返回true,不含有返回false item(索引):获取classList指定索引的类名。
2.getBoundingClientRect() 用于获取某个元素相对于视窗的位置集合。
集合中有top, right, bottom, left等属性
- dom对象.getBoundingClientRect()是DOM元素到浏览器可视范围的距离(不包含文档卷起的部分)
- dom对象.getBoundingClientRect().top 元素上边到视窗上边的距离
- dom对象.getBoundingClientRect().right 元素右边到视窗左边的距离
- dom对象.getBoundingClientRect().width 元素的宽度 (内容区+padding+border+滚动条)
注意:有了这个方法,获取页面元素的位置就简单多了。
- var x = dom对象.getBoundingClientRect().left + document.documentElement.scrollLeft;
- var y = dom对象.getBoundingClientRect().top + document.documentElement.scrollTop;