1、操作内联样式
- 通过JS来修改元素的样式
- 注意:如果CSS的样式名中含有-号,
- 通过style属性设置的样式都是内联样式
- 而内联样式有较高的优先级
- 用 !important 试试
- 通过style属性设置和读取的都是内联样式
- 它无法读取样式表中的样式
- 读取元素的当前显示的样式
- 语法:元素.currentStyle.样式名
- 用来读取当前元素正在显示的样式,只有ie支持,其他浏览器都不支持
- 在其他浏览器中可以使用:
- getComputeStyle()这个方法,这是window的方法
- 参数:
- 1、第一个参数 :要获取样式的元素
- 2、第二个 :可以传递的一个伪元素,一般都传null
- 该方法会返回一个对象,对象中封装了当前元素对应的样式
- 如果获取的样式没有设置,,则会获取到真实的值,而不是默认值
- 比如没有设置width,它不会返回auto,而是返回一个长度值
- 但是该方法不支持ie8及以下
- 通过上面的两个方式读取到内容都是只读的,不能修改
- 定义一个函数,用来获取指定元素的当前的样式
- 参数:
- 1、obj 要获取样式的元素
- 2、name 要获取的样式名
<style type="text/css">
#box1{
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
<script type="text/javascript">
window.onload = function () {
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
btn01.onclick=function () {
//使用style属性
box1.style.width="300px";
box1.style.height="300px";
box1.style.backgroundColor="red";
};
var box2 = document.getElementById("box2");
btn01.onclick=function () {
//alert(box2.style.backgroundColor)
//读取元素的当前显示的样式
alert(box1.currentStyle.width);
alert(getComputedStyle(box1,null).width)
};
};
//定义一个函数,用来获取指定元素的当前的样式
function getStyle(obj,name) {
//判断浏览器中是否有这种方法
/*if(window.getComputedStyle){
return getComputedStyle(box1,null)[name];
}else{
return obj.currentStyle[name];
}*/
/*if (obj.currentStyle){
return obj.currentStyle[name];
}else{
return getComputedStyle(box1,null)[name];
}*/
return window.getComputedStyle?getComputedStyle(box1,null)[name] :obj.currentStyle[name];
}
</script>
<body>
<button id="btn">fsdfas</button>
<br/></br/>
<div id="box1"></div>
<div id="box2"></div>
</body>
2、其他样式相关的属性
- element.clientHeight ,element.clientWidth
- 返回元素的可见高度、宽度
- 返回的都是数字,不带px,可以直接计算
- 获取的部分包括:内容区和内边距,不包括边框
- 这些属性都是只读的
- offsetHeight 、offsetWidth
- offsetParent:
- 可以获取当前元素的定位父元素
- 他会获取到当前元素最近的开启了定位的祖先元素
<style type="text/css">
#box1{
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
<script type="text/javascript">
window.onload = function () {
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
btn01.onclick = function () {
//element.clientHeight ,element.clientWidth
alert(box1.clientWidth);
};
};
</script>
<body>
<button id="btn">fsdfas</button>
<br/></br/>
<div id="box1"></div>
</body>