【问题标题】:Customizing jQuery scrolling effect自定义 jQuery 滚动效果
【发布时间】:2019-06-29 00:02:13
【问题描述】:

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

jQuery 滚动效果

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

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

谢谢!

【问题讨论】:

    标签: javascript jquery html scroll


    【解决方案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>

    【讨论】:

    • 谢谢!这正是我想要的。这个例子对于理解代码的作用和工作原理非常有帮助。我真的很感激!
    猜你喜欢
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多