javascript - jQuery/javascript : background-image, 滚动变化

标签 javascript jquery arrays background-image scrolltop

我会先说我是初学者,我的代码可能非常困惑和/或不连贯,但我还是会发布它,希望能发现这些错误。

我已经搜索了几天的答案和解决方案,我还在此处找到了有人问完全相同问题的主题: http://goo.gl/BwLzp (被认为含糊不清)所以我会尽我所能做到彻底。

到目前为止,我所拥有的是一些教程和此处摘录的组合:


概念:(会预加载大量图片设置为背景图,理论上每滚动一个整数(scrollTop),背景图都会相应变化。 )

所有图片基本命名为:imgname1.jpg、imgname2.jpg、imgname3.jpg等。 所以“imgname”与 scrollTop 号码配对。

这里是我所拥有的仅关于滚动(不是预加载)的内容:

$(function getPos() {
    var Pos = $(window).scrollTop();  // "Pos = scrollTop and is added onto imgname
return Pos;
}); 

$(function() {

$(window).scroll(function() { //Defines that this function will be triggered as the scrollbar is moving 

    var image_url = 'http://www.examplehost.com/imgname' + Pos + '.jpg'

    if (getPos()>1) { //If the vertical position of scrollbar is above 1 display imgname + Pos + .jpg (ex: imgname30.jpg) and add to url

        $("body").css('background-image', image_url);                            
    }


    else { //If the vertical position of scrollbar is at 1 display start image
        $("body").css('background-image', url("http://www.examplehost.com/imgname/0.jpg");
    }

});

}); //function ends

我不知道这有多困惑,是的,我会复习一下基础知识,因为这在我看来是合乎逻辑的,但我敢肯定这是完全错误的。然而,对于这个项目,我的知识仅限于猜测/想知道以下内容:

  • 当函数结束时,我的“}”后面需要逗号吗?例如:},
  • 是否正确打开和关闭了所有东西。
  • 这正是我的 js 文件的样子,如果出现函数被错误调用的问题,我不会感到惊讶。
  • 另外,我想使用 if (getPos()>=1) 而不是 if (getPos()>1)

可能有助于/进一步澄清的额外信息目标是图像位置保持不变,并且新的“框架”会随着每次滚动增量而接管。最终,我会居中 + 保持图像全屏显示,例如:http://www.powersmart.ca/

感谢您阅读本文,如果我违反了规则,或者如果这个问题/困境在我找不到的地方得到了更详细的解决,我深表歉意。

也就是说,想法?

最佳答案

尝试改变这个:

if (getPos()>1) { //If the vertical position of scrollbar is above 1 display imgname + Pos + .jpg (ex: imgname30.jpg) and add to url

    $("body").css('background-image', image_url);                            
}
else { //If the vertical position of scrollbar is at 1 display start image
    $("body").css('background-image', url("http://www.examplehost.com/imgname/0.jpg");
}

到:

if (getPos()>1) { //If the vertical position of scrollbar is above 1 display imgname + Pos + .jpg (ex: imgname30.jpg) and add to url

    $("body").css('background-image', 'url('+image_url+')');                            
}
else { //If the vertical position of scrollbar is at 1 display start image
    $("body").css('background-image', 'url(http://www.examplehost.com/imgname/0.jpg)');
}

关于javascript - jQuery/javascript : background-image, 滚动变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13318334/

相关文章:

javascript - 如何在 Node 中连接两个 JSON 数组对象

javascript - 为什么嵌套在标签中的 Span 会阻止其他嵌套项目单击以选择复选框?

javascript - R Shiny 仪表板 valueBox : Animation from one number to another

PHP 数组相交(某种)

c - 如何从函数返回二维字符串数组到C中的主函数? [警告]从不兼容的指针类型返回

c - malloc 和 realloc 数组给出意外输出

javascript - Google Contacts API - 如何仅过滤电子邮件联系人

javascript - Angular - 切换内容

javascript - 使用 jQuery 时是否有用于声明函数的特殊语法?

jquery - CSS 动画 : Remove class with gently transition