当前位置:编程学习 > JS >>

jquery Infinite Scroll实现鼠标滚动自动加载图片(百度图片加载)


Infinite Scroll是一种动态加载内容的方式,当网页滚动到底部时,自动载入本需要翻页才能看到的内容,在社交应用中很常见,例如新浪微博。

infinite scroll

WordPress.com已经支持了这个功能,但自己host的WordPress需要通过插件或代码添加,先介绍一下插件方法。

JetPack
如果你使用Jetpack by WordPress.com插件,那只需要一段简单的代码就可以开启infinite scroll功能,jetpack已经集成了该功能。

Infinite Scroll
直接安装Infinite-Scroll WordPress插件,如果你使用默认主题或一些知名主题,只要开启该插件就可以获得infinite scroll功能。如果是自己写的主题,就需要设置一番,完全不懂HTML的话可能会有些困难,需要设置的内容在第三节中将会提到。

不使用插件
下面介绍的方法来自WordPress Theming。

1. 下载infinite scroll的zip压缩包,在根目录下找到jquery.infinitescroll.min.js这个文件,放到主题的js目录下。

2. 挑一张ajax loader图片作为loading时显示的图片,放到主题的images目录下。

3. 注册并加载infinite scroll所需要的脚本,将下面代码放在主题的functions.php中

 

 代码如下 复制代码
/**
 * Load javascripts used by the theme
 */
function custom_theme_js() {
    wp_register_script('<span style="color: #DD4B39">infin</span>ite_scroll', get_stylesheet_directory_uri() . '/js/jquery.<span style="color: #DD4B39">infin</span>itescroll.min.js', array('jquery'), null, true);
    if (!is_singular()) {
        wp_enqueue_script('<span style="color: #DD4B39">infin</span>ite_scroll');
    }
}
add_action('wp_enqueue_scripts', 'custom_theme_js');

4. 初始化infinite scroll,这里需要你懂HTML了,这里我们要找一些相关的css selector,才能继续完成代码。

img: ajax loader gif图片的url
nextSelector: 能够选中下一页(Previous Post)链接元素的css selector
navSelector: 包含上一页/下一页链接的元素的css selector
itemSelector: 包含每篇post内容的元素的css selector
contentSelector: 包含所有文章的container元素的css selector

 

 代码如下 复制代码
/**
 * <span style="color: #DD4B39">Infin</span>ite Scroll
 */
function custom_infinite_scroll_js() {
    if (!is_singular() ) {
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function(){
            /**
             * Customize the previous navitation menu
             */
            var <span style="color: #DD4B39">infin</span>ite_scroll = {
                loading: {
                    img: "<?php echo get_stylesheet_directory_uri(); ?>/images/ajax-loader.gif",
                    msgText: "<?php _e('Loading the next set of posts...', 'tt_child'); ?>",
                    finishedMsg: "<?php _e('All posts loaded.', 'tt_child'); ?>"
                },
                nextSelector:"#nav-below .nav-previous a",
                navSelector:"#nav-below",
                itemSelector:"article",
                contentSelector:"#content"
            };
            jQuery( <span style="color: #DD4B39">infin</span>ite_scroll.contentSelector ).<span style="color: #DD4B39">infin</span>itescroll( <span style="color: #DD4B39">infin</span>ite_scroll );
        });
        </script>
        <?php
    }
}

如果使用Infinite Scroll插件时总是出错,多半是这几个selector没找对,只有找对这些class才能让代码工作。

注意:上述代码使用get_stylesheet_directory_uri获取路径,如果你需要的资源在parent theme中,请替换成get_template_directory_uri。

补充:网页制作,jquery 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,