简体   繁体   English

如何根据滚动条移动DIV的背景图像?

[英]How do I move the background image of a DIV based on the scrollbar movement?

I have been looking into parallax effects for vertical scrolling on my web page, and after some research, I'm not sure that what I want to do is technically a parallax effect. 我一直在研究网页上垂直滚动的视差效果 ,经过研究后,我不确定我想做的技术上是视差效果。

From what I've seen, most parallax effects assume you want to be able to scroll indefinitely with many background images rolling by, or with huge images that repeat. 从我所看到的,大多数视差效果都假定您希望能够无限滚动地滚动许多背景图像或重复的大图像。

What I want to do is have the background of two DIVs be filled with a background image as the scroll bar reaches the bottom of the page. 我想做的是在滚动条到达页面底部时,用背景图像填充两个DIV的背景。 Note that I do not want the background images to stretch. 请注意,我不想拉伸背景图像。 I'm assuming to get the effect I want that these images would have a vertical height bigger than most people's viewport, and then their vertical position would change. 我假设要获得想要的效果,即这些图像的垂直高度大于大多数人的视口,然后它们的垂直位置将发生变化。 When the user's scrollbar is at the top, a certain amount of the background is visible, and then it moves vertically to fill the background space as the user scrolls down. 当用户的滚动条位于顶部时,可以看到一定数量的背景,然后随着用户向下滚动它垂直移动以填充背景空间。

Please see the image below for a visual explanation of the effect I hope to acheive: 请查看下图,以直观地了解我希望达到的效果:

在此处输入图片说明

The height of the veiwport will vary depending on the length of content inside the inner DIV. veiwport的高度将根据内部DIV内部内容的长度而变化。

My trouble is that if what I am trying to do is not exactly a parallax effect, then I don't know what else to call it, and my attempts to search by describing it keep landing me back at pages offering tutorials on parallax effects. 我的麻烦是,如果我要执行的操作不完全是视差效果,那么我不知道该怎么称呼它,而通过描述它进行搜索的尝试使我回到了提供视差效果教程的页面。 So I've been stumped by a lack of terminology. 因此,我对缺乏术语感到困惑。

If someone could direct me to how I can control the vertical position of the background depending on the scrollbar position, that would be much appreciated. 如果有人可以指导我如何根据滚动条的位置控制背景的垂直位置,那将不胜感激。 If this can be done with just CSS that would be great, but I'm assuming some Javascript would be required. 如果仅使用CSS就能做到,那就太好了,但是我假设需要一些Javascript。 A jQuery solution would also work for me. jQuery解决方案也适用于我。


Update: 更新:

After searching using the terms provided in comments, I've got the background image in the outer DIV to almost do what I want with the following code: 使用注释中提供的术语进行搜索后,我在外部DIV中获得了背景图片,几乎可以通过以下代码来完成我想做的事情:

$(window).scroll(function () {
var yPos = $("#outerDiv").height() - ($("#outerDIV").height() * ($(window).scrollTop() / $(window).height()));
document.getElementById('outerDIV').style.backgroundPosition="0px " + yPos + "px";
});

It moves the background image in the right direction relative to the scrolling, but what it lacks is constraining that motion to within the viewport. 它将背景图像相对于滚动方向向正确的方向移动,但是缺少的是将运动限制在视口内。 Getting the right proportions based on the viewport and DIV sizes is proving to be just a little beyond my mathematical abilities. 事实证明,根据视口和DIV尺寸获取正确的比例仅超出我的数学能力。

For your requirement, you have to use a jquery parallax plugin to guide this activity, my best suggest it to use a Superscollorama and play with the elements as your wish... 根据您的要求,您必须使用jquery视差插件来指导此活动,我最好建议您使用Superscollorama并随心所欲地玩元素...

As far as your question, Try this example, 关于您的问题,请尝试以下示例,

controller.addTween(
    '#examples-background',
    (new TimelineLite())
    .append([
        TweenMax.fromTo($('#parallax-it-left'), 1, 
        {css:{backgroundPosition:"(0 -54px)"}, immediateRender:true}, 
        {css:{backgroundPosition:"(0 -54px)"}}),
        TweenMax.fromTo($('#parallax-it-right'), 1, 
        {css:{backgroundPosition:"(0 -54px)"}, immediateRender:true}, 
        {css:{backgroundPosition:"(0 54px)"}})
    ]),
1000 // scroll duration of tween
);

You serial vice change as far as your wish... 您可以按照自己的意愿改变副钳...

Try practice this plugin, hope that works for you... 尝试练习此插件,希望对您有用...

http://johnpolacek.github.io/superscrollorama/ http://johnpolacek.github.io/superscrollorama/

Thanks... 谢谢...

Turns out what I want to acheive is possible with no special plugins, just some carefully thought out math. 事实证明,我不需要特殊的插件就能完成我想达到的目标,只需仔细考虑一下数学即可。 I did use a little jQuery syntax, but I don't think it's strictly necessary. 我确实使用了一些jQuery语法,但是我认为这不是绝对必要的。

The code below has copious notes, so hopefully it's largely explanatory. 下面的代码有很多注释,因此希望可以在很大程度上进行解释。 In summary, you just need to find the position of the background image when the scroll would be at the top, and the position it would be if the scroll bar was at the bottom, and then you can use the percentage of the scrollbar's movement to work out where you are between those two points. 总之,当滚动条位于顶部时,您只需要查找背景图像的位置;如果滚动条位于底部,则只需查找背景图像的位置,然后可以使用滚动条的移动百分比来计算出这两点之间的位置。 It's a little tricker than just that, of course, in that you have to account for the difference between the total height of the scroll bar and where your DIV appears on the page and a few other adjustments, but the details of what I did are below. 当然,这不只是一个小技巧,因为您必须考虑滚动条的总高度和页面上DIV出现的位置之间的差异以及其他一些调整,但是我所做的细节是下面。

What I've done here is just for the "outer DIV" that I described in my question. 我在这里所做的只是针对我在问题中描述的“外部DIV”。 To get a background to move like the "inner DIV" I described, you'd have to modify the code, presumeably by reversing a few parameters. 为了使背景像我所描述的“内部DIV”那样运动,您必须修改代码,大概是通过反转一些参数。 I haven't done that yet, but it seems like a straightforward task. 我还没有做到这一点,但这似乎是一项简单的任务。

Hope others find this code useful. 希望其他人觉得此代码有用。 If anyone has suggestions on how it can be made more efficient or better, please let me know. 如果有人对如何使其更高效或更佳提出建议,请告诉我。

function moveBG(){
   // imageHeight is not the total height of the image,
   // it's the vertical amount you want to ensure remains visible no matter what.
   var imageHeight = 300;
   // Get the maximum amount within the DIV that the BG can move vertically.
   var maxYPos = $("#outerDIV").height() - imageHeight;
   // Get the amount of vertical distance from the top of the document to
   // to the top of the DIV.
   var headerHeight = document.getElementById("outerDIV").offsetTop;
   // Calculate the BG Y position for when the scrollbar is at the very top.
   var bgTopPos = $(window).height() - headerHeight - imageHeight;
   // I don't want the image to wander outside of the DIV, so ensure it never
   // goes below zero.
   if (bgTopPos < 0)
   {
      bgTopPos = 0;
   }
   // Calculate the BG Y position when the scrollbar is at the very top.
   var bgBottomPos = $(document).height() - $(window).height() - headerHeight;
   // To prevent the BG image from getting cut off at the top, make sure
   // its position never exceeds the maximum distance from the top of the DIV.
   if (bgBottomPos > maxYPos)
   {
      bgBottomPos = maxYPos;
   }
   // Subtract the top position from the bottom, and you have the spread
   // the BG will travel.
   var totalYSpan = bgBottomPos - bgTopPos;
   // Get the scrollbar position as a "percentage". Note I simply left it as a 
   // value between 0 and 1 instead of converting to a "true" percentage between
   // 0 and 100, 'cause we don't need that in this situation.
   var scrollPercent = ($(window).scrollTop() / ( $(document).height() - $(window).height()));
   // The percentage of spread is added to the top position, and voila!
   // You have your Y position for the BG image.
   var bgYPos = bgTopPos + (Math.round(totalYSpan * scrollPercent));
   // Apply it to the DIV.
   document.getElementById('outerDIV').style.backgroundPosition="0px " + bgYPos + "px";
}
// Place the BG image correctly when opening the page.
$(document).ready(function() {
   moveBG();
});
// Make it update when the scrollbar moves.
$(window).scroll(function () {
   moveBG();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM