以下是一个使用 jQuery 实现的浮动网站楼层导航的简单示例代码。该示例基于一个假设的网页结构,包含了几个楼层(section),并创建了一个浮动的楼层导航,点击导航链接可以平滑滚动到相应的楼层。
HTML结构示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Floating Floor Navigation</title> <link rel="stylesheet" href="styles.css"> </head> <body> <nav class="floor-nav"> <ul> <li><a href="#section1">Section 1</a></li> <li><a href="#section2">Section 2</a></li> <li><a href="#section3">Section 3</a></li> <li><a href="#section4">Section 4</a></li> </ul> </nav> <section id="section1"> <h2>Section 1</h2> <p>This is the content of Section 1.</p> </section> <section id="section2"> <h2>Section 2</h2> <p>This is the content of Section 2.</p> </section> <section id="section3"> <h2>Section 3</h2> <p>This is the content of Section 3.</p> </section> <section id="section4"> <h2>Section 4</h2> <p>This is the content of Section 4.</p> </section> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="script.js"></script> </body> </html>
CSS(styles.css)样式:
body { margin: 0; font-family: Arial, sans-serif; } .floor-nav { position: fixed; top: 50%; left: 20px; transform: translateY(-50%); background-color: #f0f0f0; padding: 10px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); } .floor-nav ul { list-style: none; padding: 0; } .floor-nav li { margin-bottom: 10px; } .floor-nav a { text-decoration: none; color: #333; display: block; padding: 5px; border-radius: 3px; transition: background-color 0.2s; } .floor-nav a:hover { background-color: #ddd; }
jQuery(script.js)示例代码:
$(document).ready(function() { $('.floor-nav a').on('click', function(e) { e.preventDefault(); var target = $(this).attr('href'); $('html, body').animate({ scrollTop: $(target).offset().top }, 800); }); });
在这个示例中,导航链接被点击时,通过 jQuery 的 animate 方法平滑滚动到对应的楼层。导航使用固定定位在页面左侧浮动,随着滚动而保持位置。你可以根据你的实际需求进行自定义和扩展。