实现以下目标的最佳方法是什么:
我想要一个居中的大 Logo ,当您向下滚动并成为导航栏
的一部分时,它会缩小并移动到页面的左上角
。
我还想要一个 nav bar
从顶部淡出。(我只知道如何定时不依赖于滚动)
当网站加载时,它看起来就像一个带有简单背景的 Logo 。当您向下滚动时, Logo 将移动到左上角
,导航栏
将逐渐缩小,背景图片也将移到视线之外。
有什么方法可以根据滚动的距离进行转换。所以,如果你中途停下来,你的转变也会停止吗?
最佳答案
如果我对您的理解是正确的,您想在滚动时根据滚动的程度来转换到导航栏/标题和 Logo 吗?如果是这样,它并不像听起来那么难。
首先我们必须找出您在页面上滚动了多少像素以及在转换完成之前要滚动多少像素。 Se 代码示例如下。
$(window).on("scroll", function() {
var yPos = $(this).scrollTop(),
yPer = (yPos / 120);
if (yPer > 1) {
yPer = 1;
}
});
此处找到页面的 y 位置 yPos
向下滚动 120 像素时过渡设置为完成。有了这些信息,我们就可以计算滚动像素的百分比,直到达到 120 像素; yPer
.
0px = 0%, 60px = 50%, 120px = 100%
在if
-声明我们确保百分比不能超过 100%。
HTML 和 CSS 部分
在我们进一步处理 JavaScript 部分之前,让我们设置 HTML 和 CSS。
HTML 结构:
<header></header>
<img class="logo" src="http://oi68.tinypic.com/2z5m4pu.jpg" />
在这种情况下, Logo 不在标题内,因为我们将默认隐藏标题,这也会隐藏包括 Logo 在内的所有子元素,这是我们不想要的。
隐藏标题/导航栏:
header {
width: 100%;
height: 60px;
background: #FFF;
position: fixed;
top: -60px;
opacity: 0;
}
由于您希望标题在滚动时从顶部淡入,top
设置为标题本身的负高度和 opacity
到 0。
将 Logo 居中:
img.logo {
height: 200px;
position: fixed;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0);
}
通过这种方式,无论浏览器窗口的大小和分辨率如何,我们都会将 Logo 居中放置在屏幕中间。如果 top
中的值, left
和 translate3d
全部设置为 0, Logo 将位于左上角。这就是为什么在我们的情况下这是一个很好的方法。
JavaScript 部分 - 续
现在我们准备好继续 JavaScript 部分。
在变量中存储高度:
var header = $("header"),
headerHeight = header.height(),
logo = $(".logo"),
logoHeight = logo.height();
$(window).on("scroll", function() {
// Rest of our code
});
为了让我们自己以后更容易,我们将自动找到 header
的高度和 logo
,并将它们存储在变量中。通过这样做,如果我们以后想要更改元素的高度,我们就不必更改 JavaScript 代码中的任何内容。我们只需更改它,在 CSS 中。
我们将在 scroll
之前设置这些变量-功能因为,如上所示,它们在滚动时不会改变。
计算:
var logoPos = ( -1*(yPer * 50) + 50),
logoSize = ((headerHeight * yPer) - (logoHeight * yPer) + logoHeight),
headerPos = ((yPer * headerHeight) - headerHeight);
这是我们代码中非常重要的一部分。这些表达式 是计算元素在我们滚动时应如何动画的 once。
logoPos: Calculating the new position of the logo as we scroll. We know that the
top
,left
andtranslate3d
always has a value of "50
". | Starts on50
, ends on0
.logoSize: Calculating the size of the logo as we scroll. | Starts on the height of the
logo
, ends on the height of theheader
.headerPos: Calculating the position of the header as we scroll. | Starts on the negative height of
header
, ends on0
.NOTE: If we didn’t stored the heights of your elements like before, we had to manually change them in calculations if we later wanted to change them.
添加新样式:
logo.css({
top: logoPos + "%",
left: logoPos + "%",
transform: "translate3d(-" + logoPos + "%,-" + logoPos + "%,0)",
height: logoSize
});
header.css({
top: headerPos,
opacity: yPer
});
在这里,我们在滚动时使用所有计算来设置元素的样式。关于logo
在 translate3d
我们必须记住在 logoPos
之前加一个减号.否则 Logo 将从 bottom right
开始移动而不是 center
.
对于不透明度,我们不需要计算任何东西。我们只使用 yPer
.
嗯,基本上就是这样。希望这对您有所帮助。
您可以在上下文中查看完整代码,并在这个 fiddle 中添加注释:
关于javascript - 向下滚动转换和 Logo 移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41722844/