jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。宽度自适应是指网页元素能够根据浏览器窗口或父容器的大小自动调整其宽度。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Width Adaptive</title>
<style>
.container {
width: 80%;
margin: 0 auto;
}
.box {
width: 50%;
height: 200px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Width Adaptive</title>
<style>
.container {
width: 80%;
margin: 0 auto;
}
.box {
height: 200px;
background-color: lightblue;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
<script>
$(window).resize(function() {
var containerWidth = $('.container').width();
$('.box').width(containerWidth / 2);
}).resize(); // 触发一次 resize 事件以初始化宽度
</script>
</body>
</html>
原因:
解决方法:
$(window).resize(function() {
var containerWidth = $('.container').width();
$('.box').width(containerWidth / 2);
}).resize(); // 触发一次 resize 事件以初始化宽度
通过以上方法,可以确保元素在不同屏幕尺寸下都能自适应调整宽度。
领取专属 10元无门槛券
手把手带您无忧上云