偏移量<a> href = id

时间:2019-12-03 02:28:30

标签: javascript jquery html

当我单击<a class="Navigation" id="WorldHeader" href="#WorldTitle">Go to World</a>时,我的窗口直接将div和id直接放在顶部。单击标签时,是否可以偏移窗口位置?我的标题隐藏了内容,但我想保留它。

1 个答案:

答案 0 :(得分:0)

解决方案

假设基于JQuery标记并使用reference@WebMarie,以下解决方案必须为您提供帮助:

$('#WorldHeader').on('click', function(event) {
  event.preventDefault(); // Prevent the default <a> action.

  let myOffset = 50; // Pixels.
  let newScrollPosition = $("#WorldTitle").offset().top - myOffset;

  $('html, body').scrollTop(newScrollPosition); // Set the current vertical position of the scroll bar.
});

带有动画:

$('#WorldHeader').on('click', function(event) {
  event.preventDefault();

  let myOffset = 50; // Pixels.
  let animationDuration = 1000; // Miliseconds.
  let newScrollPosition = $("#WorldTitle").offset().top - myOffset;

  $('html, body').animate({
    scrollTop: newScrollPosition // Set the current vertical position of the scroll bar.
  }, animationDuration);
});

使用示例

$('#WorldHeader').on('click', function(event) {
  event.preventDefault();

  let myOffset = 50; // Pixels.
  let animationDuration = 1000; // Miliseconds.
  let newScrollPosition = $("#WorldTitle").offset().top - myOffset;

  $('html, body').animate({
    scrollTop: newScrollPosition // Set the current vertical position of the scroll bar.
  }, animationDuration);
});
#WorldTitle {
  margin: 20px 0;
  width: 100%;
  height: 150px;
  background-color: red;
}

.blue {
  width: 100%;
  height: 500px;
  background-color: blue;
}

.green {
  width: 100%;
  height: 500px;
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="Navigation" id="WorldHeader" href="#WorldTitle">Go to World</a>
<div class="blue"></div>
<div id="WorldTitle"></div>
<div class="green"></div>