700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 原生js和jQuery获取元素的宽高比较

原生js和jQuery获取元素的宽高比较

时间:2023-09-07 03:40:34

相关推荐

原生js和jQuery获取元素的宽高比较

截图效果和盒子模型:

在jQuery中,width()方法用于获得元素宽度;

innerWidth()方法用于获得包括内边界(padding)的元素宽度;

outerWidth()方法用于获得包括内边界(padding)和边框(border)的元素宽度;

如果outerWidth()方法的参数为true则外边界(margin)也会被包括

测试demo代码:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>获取元素不同的宽度</title><style>*{padding:0;margin:0;}body{background-color: pink;}#box{width:100px;height:50px;padding:10px;border:20px solid blue;margin:30px;background-color: purple;color:white;}</style></head><body><div id="box">我是box的内容,我是box的内容content</div><script src="/jquery/3.3.1/jquery.min.js"></script><script>// 原生js写法var box = document.getElementById('box');// 这种写法是错误的,没有该方法console.log(box.width);//undefinedconsole.log(box.height);//undefined// 注意此方法拿到的值带有单位pxconsole.log(window.getComputedStyle(box).width);//100pxconsole.log(window.getComputedStyle(box).height);//50pxconsole.log('offsetWidth为元素width(100)+padding(10*2)+border(20*2)' + box.offsetWidth);//160console.log('offsetHeight为元素height(50)+padding(10*2)+border(20*2)' + box.offsetHeight);//110console.log('clientWidth为元素width(100)+padding(10*2)' + box.clientWidth);//120console.log('clientHeight为元素height(100)+padding(10*2)' + box.clientHeight);//70/***jQuery 写法*/var jw = $('#box').width();//100var jh = $('#box').height();//50console.log(jw);console.log(jh);var jinw = $('#box').innerWidth();//120var jinh = $('#box').innerHeight();//70console.log(jinw);console.log(jinh);var joutw = $('#box').outerWidth();//160var jouth = $('#box').outerHeight();//110// 传入参数true,那么margin (top 和 bottom)也会被包含。var joutw = $('#box').outerWidth(true);//220var jouth = $('#box').outerHeight(true);//170console.log(joutw);console.log(jouth);</script></body></html>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。