要使用 JavaScript 实现浮动布局,可以使用 CSS 定位属性并添加一些 JavaScript 代码,以根据屏幕大小动态调整布局。下面是一个示例代码片段,演示如何使用 HTML 和 CSS 创建浮动布局:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>浮动布局演示-模站无忧</title>
<link rel="stylesheet" href="styles.<a target="_blank" href="https://mz5u.cn/tag/css" title="View all posts in css">css</a>">
</head>
<body>
<header>
<h1>模站无忧演示代码</h1>
</header>
<main>
<section id="intro">
<h2>欢迎来到模站无忧( www.mz5u.cn)!</h2>
<p>这是一条浮动布局演示</p>
</section>
<section id="about">
<h2>About Me</h2>
<p>我是一名Web开发人员和设计师,热衷于创建美丽且用户友好的网站。.</p>
</section>
</main>
<footer>
<p>© 2023 模站无忧 Mz5u.cn</p>
</footer>
<script src="script.js"></script>
</body>
</html>
CSS
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f2f2f2;
}
header {
background-color: #333;
color: #fff;
padding: 20px;
}
header h1 {
margin: 0;
}
main {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
min-height: 100vh;
background-color: #fff;
}
#intro, #about {
flex: 1;
padding: 20px;
text-align: center;
}
#intro h2, #about h2 {
margin: 0;
font-size: 2.5em;
}
#intro p, #about p {
font-size: 1.2em;
line-height: 1.5;
}
footer {
background-color: #333;
color: #fff;
padding: 20px;
}
footer p {
margin: 0;
text-align: center;
}
Js代码
//模站无忧 网站浮动布局<a target="_blank" href="https://mz5u.cn/tag/js" title="View all posts in Js">Js</a>代码
const introSection = document.getElementById('intro');
const aboutSection = document.getElementById('about');
const footer = document.getElementById('footer');
// 布局设置
introSection.style.display = 'block';
aboutSection.style.display = 'none';
footer.style.display = 'block';
// 将滚动事件侦听器添加到主容器
document.querySelector('main').addEventListener('scroll', () => {
// 检查用户是否已滚动绕过介绍部分
if (window.innerHeight >= introSection.offsetTop + introSection.offsetHeight) {
// 显示相关部分
introSection.style.display = 'none';
aboutSection.style.display = 'block';
footer.style.display = 'none';
} else {
// 隐藏相关部分
aboutSection.style.display = 'none';
introSection.style.display = 'block';
footer.style.display = 'block';
}
});
此代码使用 CSS 定位属性创建一个浮动布局,并添加一些 JavaScript 代码以根据屏幕大小动态调整布局。“主”容器设置为具有“flex”布局,带有“flex-wrap:wrap”以允许多个元素换行到新行上。“两端对齐内容”和“对齐项”属性用于使容器内的元素居中。
“display: none”属性最初用于隐藏“关于”部分,“display: block”属性用于在用户滚动到介绍部分时显示它。“页脚”元素始终显示在页面底部。