设置一个固定元素并滚动另一个 - 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 xx_src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script xx_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>

这将产生以下输出。该元素固定在上方,其他元素在滚动上可见,如下所示 -

猜你喜欢