javascript - 自定义jQuery滚动效果

标签 javascript jquery html scroll

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

jQuery滚动效果

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

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

谢谢!

最佳答案

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

$('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>

关于javascript - 自定义jQuery滚动效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56814170/

相关文章:

javascript - 如何在客户端调用fetch方法从服务器端接收数组?

javascript - 如何识别 AJAX 或 XMLHttpRequest 调用中的调用函数名称?

javascript - 每当我点击网站内的页面链接时,我都会注销,如何修复?

javascript - 使用 HTML 或 JavaScript 重命名后下载文件

html - 如何使 div 扩展到屏幕分辨率而不是内容?

Javascript点击开始/停止间隔函数

javascript - 如何更改嵌套在按钮中的跨度的内容?

javascript - 如何使用 jquery 将文本字段值复制到剪贴板?

html - 将我的菜单栏中的按钮居中

javascript - 无序列表、列表项、JS/HTML 问题