0

我正在一个网站上工作,我使用 jQuery 制作了一个简单的滚动效果。基本上,当用户单击其中一个导航链接时,我只是让页面滚动到指定部分。我想对此进行自定义,以便标题(我用作滚动目标)不在页面的最顶部。我更希望它在中间。有人知道我如何轻松定制这个吗?下面是我的 jQuery 代码。

jQuery 滚动效果

$('a[href*="#"]').on('click', function(e) {
e.preventDefault()

$('html, body').animate(
  {
    scrollTop: $($(this).attr('href')).offset().top,
  },
  500,
  'linear'
)
 });

谢谢!

4

1 回答 1

1

关键是计算偏移量,试试这个:

$('a[href*="#"]').on('click', function(e) {
	e.preventDefault()

	var id = $(this).attr('href');
	var $element = $(id);
	var elementHeight = $element.height();
	var winHeight = $(window).height();
	var offset;
	if(elementHeight >= winHeight) //if element height > window height, just put the element to top place.
	{
		offset = 0;
	}
	else // else make it to the middle place of window.
	{
		offset = Math.round((elementHeight - winHeight) / 2);
	}

	$('html, body').animate(
	  {
	    scrollTop: $element.offset().top + offset,
	  },
	  500,
	  'linear'
	)
 });
body, html {
  padding: 0;
  margin: 0;
}

.nav-wrap {
  width: 100vw;
  position: fixed;
  background: rgba(0,0,0,0.5);
  padding: 10px;
}

.nav-wrap > a {
  color: #ffffff !important;
  padding: 10px;
}

section {
  display: block;
  width: 100vw;
}

#id1 {
  background: #ff0000;
  height: 50vh;
}
#id2 {
  background: #00ff00;
  height: 80vh;
}
#id3 {
  background: #ffff00;
  height: 120vh;
}
#id4 {
  background: #0000ff;
  height: 30vh;
}
#id5 {
  background: #000000;
  height: 60vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav-wrap">
  <a href="#id1">ID1</a>
  <a href="#id2">ID2</a>
  <a href="#id3">ID3</a>
  <a href="#id4">ID4</a>
  <a href="#id5">ID5</a>
</div>
<div class="section-wrap">
  <section id="id1"></section>
  <section id="id2"></section>
  <section id="id3"></section>
  <section id="id4"></section>
  <section id="id5"></section>
</div>

于 2019-06-29T01:18:13.773 回答