jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。在处理页面元素的高宽时,jQuery 提供了一系列方便的方法。
height()
:获取元素的高度(不包括边框、内边距和外边距)。innerHeight()
:获取元素的高度(包括内边距)。outerHeight()
:获取元素的高度(包括内边距和边框)。outerHeight(true)
:获取元素的高度(包括内边距、边框和外边距)。height(value)
:设置元素的高度。innerHeight(value)
:设置元素的内边距高度。outerHeight(value)
:设置元素的内边距和边框高度。outerHeight(value, true)
:设置元素的内边距、边框和外边距高度。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 高宽示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="box" style="width: 200px; height: 200px; background-color: lightblue;">
Click me to change size!
</div>
<script>
$(document).ready(function() {
$('#box').click(function() {
var currentHeight = $(this).height();
var newHeight = currentHeight + 50;
$(this).height(newHeight);
});
// 获取元素高宽
console.log('Height:', $('#box').height());
console.log('Inner Height:', $('#box').innerHeight());
console.log('Outer Height:', $('#box').outerHeight());
console.log('Outer Height with Margin:', $('#box').outerHeight(true));
});
</script>
</body>
</html>
$(document).ready()
或 $(window).load()
。display: none
或 visibility: hidden
。!important
提高优先级。通过以上方法,可以有效地处理页面元素的高宽问题,提升用户体验和页面交互效果。
领取专属 10元无门槛券
手把手带您无忧上云