設定固定元素並滾動另一元素 - jQuery
假設以下是我們固定的元素 div −
<div class="fixedElement"> Fixed </div>
修復以上元素的 CSS 樣式 −
.fixedElement {
position: fixed;
background-color: skyblue;
top: 0;
left: 0;
right: 0;
}以下是我們需要滾動的元素 −
<div id="scrollDemo"> David Miller </div>
現在,使用 window.scrollTo()。
示例
讓我們看看完整的程式碼 −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
.fixedElement {
position: fixed;
background-color: skyblue;
top: 0;
left: 0;
right: 0;
}
html,
body {
height: 1000px;
}
#scrollDemo {
position: relative;
top: 500px;
}
</style>
<body>
<div class="fixedElement">
Fixed
</div>
<div id="scrollDemo">
David Miller
</div>
</body>
<script>
window.scrollTo(0, document.getElementById('scrollDemo').offsetTop - document.getElementsByClassName('fixedElement')[0].offsetHeight);
</script>
</html>這樣將會產生如下輸出。元素已固定在上方,其他元素在滾動時可見,如下所示 −

廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP