css部分
给body设置背景颜色仍然铺满屏幕
场景:给body限定宽和高,并设置了背景颜色
结果:发现浏览器全屏都是body的背景颜色
通过浏览器的开发者工具我们发现body元素的效果与预期一致
解决方案:给html元素设置背景颜色为白色即可。
原因:当html未设置背景颜色时,默认以body的背景颜色为准。
一些使用的CSS属性
禁止选中
user-select: none: 给元素设置该属性后,就不会出现选中元素高亮的效果啦~
js部分
原生方式获取元素样式表中的属性
我们知道,在原生js中,可以通过element.style.xxx的方式给元素设置样式,并且这种方式设置的是内联样式:
<body>
<div>234</div>
</body>
<script>
let div = document.querySelector("div");
div.style.width = "200px";
<script/>
在浏览器中,我们进行验证:
通过嵌入式的方式设置样式,然后通过js进行获取,看看能否读取到:
<head>
<style>
div {
background-color: skyblue;
}
</style>
</head>
<body>
<div>234</div>
</body>
<script>
let div = document.querySelector("div");
div.style.width = "200px";
console.log(div.style.backgroundColor);
<script/>
结果我们发现控制台输出为空,即没有获取到,这是因为通过原生
element.style.xxx的方式读取样式,仍然是读取的内联样式,而无法读取到嵌入式设置的样式表中的样式:
<head>
<style>
div {
background-color: skyblue;
}
</style>
</head>
<body>
<div style="height: 400px">234</div>
</body>
<script>
let div = document.querySelector("div");
div.style.width = "200px";
console.log(div.style.backgroundColor);
console.log(div.style.height);
<script/>
虽然该方法无法读取到嵌入式设置的样式表中的样式,但是
window属性中有一个叫getComputedStyle的属性,可以获取到样式表中的样式,语法:window.getComputedStyle(obj, pseudoElt)
- obj:要获取的元素
- pseudoElt:指定一个要匹配的伪元素的字符串,通常设置为
null。 - 返回值:
style是一个实时的对象,当元素的样式更改时,它会自动更新本身。
// 其余代码同上
let color = window.getComputedStyle(div, null)["backgroundColor"];
console.log(color); // rgb(135, 206, 235)
因此,想要读取样式表中的样式,直接使用该方法即可,需要注意的是,该方法对于IE浏览器,只支持IE9+的版本,对于IE8-的版本支持的是element.currentStyle这个属性,如果想要兼顾兼容性问题的话,最好是单独封装出一个函数:
function getStyle(ele, name) {
if(window.getComputedStyle) {
return window.getComputedStyle(ele, null)[name];
} else {
// IE8
return ele.currentStyle[name];
}
// 简洁写法:return window.getComputedStyle ? window.getComputedStyle(ele, name)[name] : ele.currentStyle[name];
}