如何利用 JavaScript 实现网站浮动布局

如何利用 JavaScript 实现网站浮动布局

要使用 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.css">
</head>
<body>
  <header>
    <h1>模站无忧演示代码</h1>
  </header>
  <main>
    <section id="intro">
      <h2>欢迎来到模站无忧( mz5u.cn)!</h2>
      <p>这是一条浮动布局演示</p>
    </section>
    <section id="about">
      <h2>About Me</h2>
      <p>我是一名Web开发人员和设计师,热衷于创建美丽且用户友好的网站。.</p>
    </section>
  </main>
  <footer>
    <p>&copy; 2023 模站无忧 Mz5u.cn</p>
  </footer>
  <script src="script.js"></script>
</body>
</html>
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代码

const introSection = document.getElementById('intro');
const aboutSection = document.getElementById('about');
const footer = document.getElementById('footer');

// Set the initial layout
introSection.style.display = 'block';
aboutSection.style.display = 'none';
footer.style.display = 'block';

// Add a scroll event listener to the main container
document.querySelector('main').addEventListener('scroll', () => {
  // Check if the user has scrolled past the intro section
  if (window.innerHeight >= introSection.offsetTop + introSection.offsetHeight) {
    // Show the about section
    introSection.style.display = 'none';
    aboutSection.style.display = 'block';
    footer.style.display = 'none';
  } else {
    // Hide the about section
    aboutSection.style.display = 'none';
    introSection.style.display = 'block';
    footer.style.display = 'block';
  }
});

此代码使用 CSS 定位属性创建一个浮动布局,并添加一些 JavaScript 代码以根据屏幕大小动态调整布局。“主”容器设置为具有“flex”布局,带有“flex-wrap:wrap”以允许多个元素换行到新行上。“两端对齐内容”和“对齐项”属性用于使容器内的元素居中。

“display: none”属性最初用于隐藏“关于”部分,“display: block”属性用于在用户滚动到介绍部分时显示它。“页脚”元素始终显示在页面底部。

原创文章禁止随意转载,转载需得到授权

 

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享