如何使用填充滚动到元素的顶部?

时间:2019-02-05 00:05:23

标签: javascript jquery html css anchor

我们有一个水平跳转菜单,该菜单将根据菜单项的<h3 class="heading">将某人导航到href标签的顶部。由于某些原因,当有人单击菜单项时,页面导航到<h3>元素的顶部,而不是该元素的顶部(包括padding)。

问题:

  • 如何导航到其中包含padding的元素的顶部?

当前问题:

issue with jump menu

所需结果:

desired results jump

代码

// Shorthand for $( document ).ready()
$(function() {
  $(window).on('scroll', function() {
    $('.menu').addClass('menu--fixed');
  });
 $('.menu li a').on('click', function(evt) {
  var menuHeight = $('.menu').outerHeight(true);
  var elementOffset = ($(this).offset().top) - (menuHeight);
  $('html, body').stop().animate({
    scrollTop: elementOffset
  }, 2000);
  evt.preventDefault();
 });
});
.container {
	max-width: 480px;
}
.heading {
	padding: 32px;
	background-color: #eee;
}
ul {
	list-style: none;
}
.menu {
	position: relative;
	background-color: black;
	color: white;
	width: 100%;
	display: flex;
	justify-between: space-between;
	
}
.menu li {
	display: block;
	height: 100%;
}

.menu a {
	color: white;
	padding: 32px;
}

.menu--fixed {
	position: fixed;
    top: 0;
    left: 0;
    margin-top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="menu__wrapper">
<ul class="menu">
	<li><a href="#el1">element 1</a></li>
	<li><a href="#el2">element 2</a></li>
	<li><a href="#el3">element 3</a></li>
</ul>
</div>
<div class="wrapper">
	<h3 class="heading" id="el1">Lorem ipsum dolor sit amet, consectetur adipisicing elit</h3>
	<p>Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

<p>Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit amet.</p>


<p>Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

<p>Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta del veritas.</p>
</div>

<div class="wrapper">
	<h3 class="heading" id="el2">A Guide to Solving Web Development Problems</h3>
	<p>Epicurus autem, in quibus sequitur Democritum, noil fere labitur, Quam- quam utriusque cum mutta non prolx). turn illiid in priniis, quoJ, cum in rerum nalura duo quaerenda sint, ununi quae materia sit ex qua quaeque res cfficiatur, alterum quae vis sit quae quidque efficiat, de materia disserucrunt, vim et causam efficiendi reliquerunt. Sed lioc commune vitiuni; illae Epicur propriae ruinae: censet enim eadem ilia indlvidua e solida corpora ferri deorsum suo pondere ad lineam i hunc naturalem esse omnium corporum motuni.</p>

<p>Deinde ibidem homo acutus, cam illud occorreret, j omnia deorsum e regione ferrentur et, ut dixi, ad lineam, numquam fore ut atomus altera alteram posset attingere, itaque attulit rem commenticiam.</p>

<p>Declinare dixit atomum perpaulum, quo nihil posset fieri minus; ita eifici complexiones et copulationes et adhaesiones atomorum inter se, ex quo eificeretur mundus omnesque partes mundi quaeque in eo essent. Quae cum res tota fieta sit piieriliter, turn ne efficit quidem^ quod vult. Nam et ipsa declinatio ad libidinem fiiigitur - ait enim deelinare atomum sine causa, quo nibil turpius physico quam fieri.</p>



<p>This is about how to solve technical problems that arise from using front or back end technologies to make web pages or apps but some of these steps will be applicable to solving technical problems in general.</p>

<p>Half the technical problems in development are caused by something trivial but for all the problems past this level, you'll probably need to do some structured thinking.</p>
</div>

<div class="wrapper">
	<h3 class="heading" id="el3">Tempore intellegi convenire</h3>

<p>Qui autem alia matunt scribi a nobis, aequi esse debent, quod et seripta multa sunt, sic ut plura nemini e nostris, et scribentur fortasse plura et tamen qui diligenter haec quae de philosophia Htteris mandamus legere assueverit, iudicabit nulla ad legendum his esse potiora.</p>
<p>Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis dolor repellendus. Qua temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae pondere ad lineam. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat</p>

</div>
	
</div>

2 个答案:

答案 0 :(得分:0)

页面顶部和菜单之间当前存在间隙。使用position: fixed;时,您需要指定自己的最高职位。 如果您希望菜单停留在顶部,请使用top: 0px;

此外,菜单上有默认的margin-top,因此您也需要将其删除。

.menu--fixed {
  position: fixed;
  top: 0;
  left: 0;
  margin-top: 0;
}

使用此值来适应Javascript中菜单的高度应该更容易。(为此您还需要删除margin-bottom)。

$(document).ready(function(){
  $(window).on('scroll', function() {
    $('.menu').addClass('menu--fixed');
  });

  $('.menu a').click(function(e){
    e.preventDefault();
    // Get clicked anchor href.
    var anchorID = $(this).attr('href');
    // Get scroll position of the target location.
    var scrollDestination = $(anchorID).offset().top;
    // Cater for menu height
    var finalScroll = scrollDestination - 
$('.menu').outerHeight(true);
    $('html, body').animate({
        scrollTop: finalScroll
    }, 2000);
  });  
});

编辑:Javascript。

答案 1 :(得分:0)

我看到的主要问题是单击处理功能中的this是菜单中的link元素,因此为计算而获取它的偏移量与您实际的<h3>元素无关正在尝试滚动到。

此外,如果这是滚动时所需的行为,为什么不总是保持菜单固定不变?在第一个滚动事件上将其更改为固定会更改容器的布局并抛出间距。在我的示例中,我将菜单移出了容器,并使其永久固定。然后,我在.container元素的顶部添加了填充,以使当scrollTop为0(在页面加载时)时,它在固定菜单下呈现。

然后,我使用单击菜单href元素的<a>属性来查找具有相同ID的<h3>元素。使用实际的<h3>元素的偏移量进行计算可以得出所需的结果。

在CodePen上查看我的示例:https://codepen.io/bdoughty2018/pen/MLvJOd