0

我有一个功能可以将我的索引页面滚动到特定的锚标记并更改背景图像。我现在遇到的问题是我需要使用菜单页面中的链接移动到索引页面中的锚点并更改该背景图像。我的菜单页面出现在我的索引页面的顶部。

我在索引页面中滚动的 Javascript 是:

    $('-Button-to-scroll-is-clicked').click(function () {
        clearInterval(ID);
        $('html, body').animate({
            scrollTop: $('-Anchor').position().top
        },
        3000);
        var IntID = setInterval(changeImg, 1500);
        function changeImgHome() {
            $('.imagemhome').css('background', 'url(-New-Image.jpg) top center no-repeat fixed');
        };
        ID = IntID;
        return false;
    });

我用于从菜单页面滚动索引页面的 Javascript 是:

     $('-Button-In-Menu-Page').click(function () {
         $('html, body').animate({
             scrollTop: $('-Anchor-In-Index-Page').position().top
         },
         3000);
         return false;
     });

正如我所说,我需要在我的索引页面中检查我在滚动后所处的位置(使用 window.scroll 函数),以便我可以适当地更改背景图像。

4

2 回答 2

1

好吧,首先,位置收集元素的位置。默认情况下,元素是内联放置的,并且具有静态位置并且没有位置坐标,因此使用 .position().top 将无法产生页面位置,除非您已经将所有这些东西都放在绝对位置。

不过这不是问题,因为我们有.offset。偏移量告诉您目标相对于文档的 x 和 y 位置,因此我们将使用它。

现在我们的函数应该是这样的

window.onready = function(){
    $(-Button-to-scroll).on('click',function(){
       var itemPos = $('target').offset().top;
       $('body,html').animate({scrollTop:itemPos},3000);
       $('.imagemhome').css('background', 'url(-New-Image.jpg) top center no-repeat fixed');
    }
}

编辑:用于您的滚动。这不是最有效的方法,因为它基本上会在每次用户滚动时不断重写您的背景图像。

$('html').on('scroll',function(){
    var top = $(this).offset().top
    if ((top >= 200)||(top <= 300)){
        $('.imagemhome').css('background', 'url(-New-Image.jpg) top center no-repeat fixed');
    }
});
于 2013-01-29T18:24:26.037 回答
0

可以使用 检索您在页面上的当前位置$(window).scrollTop()

于 2013-01-29T18:14:58.520 回答