目录
操作内联样式
通过JS修改元素的样式---->修改的都是内联样式(有较高的优先级)
语法:元素.style.样式名 通过style属性设置和读取的都是内联样式 无法读取样式表中的样式
通过style读取到的是内联样式,无法读取样式表中的样式
<script type="text/javascript">
window.onload = function(){
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
btn01.onclick = function(){
//修改box1大小
box1.style.width = "100px";
box1.style.backgroundColor = "darkgrey";
//如果css样式名中含有 - 号,这种名称在js中是不合法的------>修改为驼峰命名法
};
//通过style读取到的是内联样式,无法读取样式表中的样式
var btn02 = document.getElementById("btn02");
btn02.onclick = function(){
alert(box1.style.backgroundColor);
}
};
</script>
获取元素的样式
只有ie支持
获取元素当前显示的样式 ---->元素.currentstyle.样式名
不支持ie8
其他浏览器中使用getComputedStyle
- 要获取元素的样式
- 可以传一个伪元素,一般都传null
都是只能看不能修改
处理兼容性问题:不必判断浏览器的版本,可以直接判断浏览器中是否有该方法
<script type="text/javascript">
window.onload = function(){
//读取样式
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
btn01.onclick = function(){
//获取元素当前显示的样式
//元素.currentstyle.样式名
//如果当前元素没有,则为默认样式
/*alert(box1.currentStyle.backgroundColor);*/
//getComputedStyle
//返回一个对象,封装了当前元素的样式
alert(getComputedStyle(box1,null).width);
//如果获取的样式没有设置,则会获取到真实的值
//alert(gegetStyle(box1,"width"));
};
};
//自定义一个方法
//需要判断浏览器中是否具有该方法
function getStyle(obj,name){
//避免报错,变量变为属性返回undefined
/*if(window.getComputedStyle){
//正常
return getComputedStyle(obj,null)[name];
}else{
//ie8
return obj.currentStyle[name];
}*/
return window.getComputedStyle?getComputedStyle(obj,null)[name];
//return getComputedStyle(obj,null)[name];正常浏览器
//return obj.currentStyle[name];//ie
};
其他样式属性:
只读取,不修改
clientWidth clientHeight 元素的可见宽度和高度 (返回的都是数值,可以直接进行计算)---->包括内容区和内边距
offsetHeight,获取元素的整个宽度和高度 包括内容区,内边距和边框
offsetParent 定位父元素----> 获取离当前元素最近的的开启了定位的祖先元素-----如果所有的祖先元素都没有开启定位,则返回body
offsetLeft 相对于其定位父元素的水平偏移量
offsetTop 相对于其定位父元素的垂直偏移量
scrollHeight 获取元素滚动区域的高度
scrollWidth 获取元素滚动区域的宽度
scrollLeft 水平滚动条滚动距离
scrollTop 水平滚动条滚动距离
判断滚动条是否滚动到底
- 垂直滚动条
scrollHeight - scrollTop = clientHeight
- 水平滚动
scrollWidth - scrollLeft = clientWidth
<script type="text/javascript">
window.onclick = function(){
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
var box4 = document.getElementById("box4");
btn01.onclick = function(){
/*box1.clientWidth;*/
/*alert(box1.offsetHeight);*/
//alert(box1.offsetParent);//定位父元素
//alert(box1.offsetLeft);//水平偏移量
//alert(box1.offsetTop);//垂直偏移量
//alert(box4.scrollHeight);//滚动的高度
//alert(box4.scrollWidth);//滚动的宽度
box4.scrollLeft;//水平滚动条滚动距离
box4.clientHeight;
//满足scrollHeight-scrollTop==clientHeight时候说明 滚动条滚到底了
}
}
</script>