css常用操作
文章目录
获取元素宽高
1、只能获取内联样式
var ele = document.getElementById('element');
console.log(ele.style.width); // 空字符串
console.log(ele.style.height); // '100px'2、可获取实时的style
var ele = document.getElementById('element');
console.log(window.getComputedStyle(ele).width); // '100px'
console.log(window.getComputedStyle(ele).height); // '100px'3、Element.currentStyle.width/height
功能与第二点相同,只存在于旧版本IE中(IE9以下),除了做旧版IE兼容,就不要用它了。
4、除了能够获取宽高,还能获取元素位置等信息
var ele = document.getElementById('element');
console.log(ele.getBoundingClientRect().width); // 100
console.log(ele.getBoundingClientRect().height); // 100取整
1.取整
1. // 丢弃小数部分,保留整数部分
2. parseInt(5/2) // 22.向上取整
1. // 向上取整,有小数就整数部分加1
2. Math.ceil(5/2) // 33.向下取整
1. // 向下取整,丢弃小数部分
2. Math.floor(5/2) // 24四舍五入
1. // 四舍五入
2. Math.round(5/2) // 3取余
1. // 取余
2. 6%4 // 2
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论