简体   繁体   English

后台切换器,当div到达页面顶部时

[英]Background switcher, when a div hits top of the page

I've been trying for a while to get this completely working now and perfecting the code, but I am still a rooky javascript programmer so I decided to ask for help. 我一直在尝试使它现在完全正常运行并完善代码,但是我仍然是一个新手javascript程序员,因此我决定寻求帮助。

What I want the script to do is, when a div hits to top(or bottom) of the page the body background changes. 我要脚本执行的操作是,当div到达页面顶部(或底部)时,主体背景会更改。

My current script to make this happen is. 我当前实现这一目标的脚本是。

        function bg_switch() 
        {
            var window_top = $(window).scrollTop();  
            var div_top = $('#post12').offset().top;
            var div_top_1 = $('#post10').offset().top;
            var div_top_2 = $('#post8').offset().top;
            var div_top_3 = $('#post1').offset().top;
            if (window_top > (div_top) ) 
            {
                $("body").css({"backgroundImage":"url(<?php bloginfo( 'template_url' );?>/img/bg/bg-join-us.jpg)"});                    
            }  

            if (window_top > (div_top_1) ) 
            {
                $("body").css({"backgroundImage":"url(<?php bloginfo( 'template_url' );?>/img/bg/bg-about-us.jpg)"});                   
            }

            if (window_top > (div_top_2)) {
                $("body").css({"backgroundImage":"url(<?php bloginfo( 'template_url' );?>/img/bg/bg-contact.jpg)"});                    
            }

            if (window_top > (div_top_3)) {
                $("body").css({"backgroundImage":"url(<?php bloginfo( 'template_url' );?>/img/bg/bg-bf4-join-us.jpg)"});                    
            }       
        }

        $(function () {
            $(window).scroll(bg_switch);
            bg_switch();
        }); 

As you can see this isn't really good code, it also doesn't change the background back for the first post. 如您所见,这并不是真正的好代码,也不会改变第一篇文章的背景。

Here is a website where I am working on and trying to get this principle work, so you guys see for yourself. 这是我正在努力的网站,试图使这一原理发挥作用,所以你们自己看看。 http://neutralgaming.nl/NeutralGaming/ (sorry for the slow loading page, bad host) http://neutralgaming.nl/NeutralGaming/ (对不起,加载页面缓慢,主机错误)

Thanks for your time 谢谢你的时间

The jQuery plugin Waypoints might help you out a lot here. jQuery插件Waypoint可能会在这里为您提供很多帮助。 You can basically set your own offsets and then return something when the browser is at that position from the top, for example: 您基本上可以设置自己的偏移量,然后在浏览器从顶部移至该位置时返回一些内容,例如:

$('#div_top').waypoint(function() {
  $(this).css({
    'background' : 'url(../path/to/img.jpg) no-repeat;'
}, { offset: 0 });

So, this will change the background image of #div_top when its offset is 0 from the top. 因此,当#div_top与顶部的偏移量为0时,这将更改#div_top的背景图像。

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

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