[英]Center a section when using smooth scroll
我正在使用克里斯·费迪南迪(Chris Ferdinandi)的“平滑滚动”脚本,并且尝试将其滚动到某个元素,但是将其居中放置。 与http://www.spotify.com上的操作类似。
我试图将以下代码添加到脚本的开头:
$(document).ready(function(){
$('.downarrow a').click(elementhref = $('.downarrow a').attr('href'));
var elementheight = $(elementhref).height();
var windowheight = $(window).height();
if (elementheight < windowheight) {
topoffset = ((windowheight / 2) - (elementheight / 2) - 30);
} else {
topoffset = 0;
}
});
然后,我将变量topoffset
添加到脚本中,以使锚点的位置偏移正确的数量。
var endLocation = _getEndLocation( document.querySelector(anchor), topoffset ); // Scroll to location
它非常适合第一部分,但是当我单击下一个.downarrow a
元素时,我的代码仅使用第一部分的高度。 但是在我的HTML中,我有几个这样的链接具有相同的类。
这是我所拥有的简化版本:
<section id="home">
<!--content-->
<div class="downarrow"><a data-scroll href="#about">Scroll Down</a></div>
</section>
<section id="about">
<!--content-->
<div class="downarrow"><a data-scroll href="#portfolio">Scroll Down</a></div>
</section>
<section id="portfolio">
<!--content-->
<div class="downarrow"><a data-scroll href="#contact">Scroll Down</a></div>
</section>
<section id="contact">
<!--content-->
</section>
我试图让它根据单击的元素来更改elementhref
变量,但这显然不适用于我的代码。 我尝试给每只downarrow
分配一个唯一的ID,但对我来说太复杂了。
这是我第一次使用JavaScript和jQuery,因此我希望有一个被忽略的简单解决方案。
尝试
(function() {
function setStuff(elementhref) {
var elementheight = $(elementhref).height();
var windowheight = $(window).height();
if (elementheight < windowheight) {
topoffset = ((windowheight / 2) - (elementheight / 2) - 30);
} else {
topoffset = 0;
}
}
$('.downarrow a').click(function() {
setStuff( $(this).attr('href') );
});
})();
仅针对您已“单击”的对象- this
-并使其成为jquery对象,以便您可以访问jquery方法$(this)
编辑/更新-在零件中添加了将点击处理程序与功能连接到dostuff
的功能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.