如何使用纯javascript在静态页面中制作无限页面滚动效果

时间:2015-12-09 14:14:17

标签: javascript php html infinite-scroll

我在网上搜索过,主要使用jquery和一些库来完成。我想知道如何使用纯javascript来制作像Twitter这样的无限页面滚动效果,而不必包含任何库(这里我把搜索php和html代码作为参考,我想在搜索结果中实现效果。我使用laravel作为后端)。我刚刚开始学习javascript,请把我当成一个10岁的男孩。感谢

// HTML

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Risky Jobs - Search</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>

   <div class="searchWrapper">
      <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method='get' >
        <input type="search" name="search">
      </form>
   </div>

   <h3>Risky Jobs - Search Results</h3>

</body>
</html>

// PHP

function build_query($user_search, $sort){
    $search_query = "SELECT * FROM posts";

    $clean_search = str_replace(',',' ',$user_search);
    $search_words = explode(' ', $clean_search);
    //to  become a array

    $final_search_words = array();
    if(count($search_words) > 0){
        foreach($search_words as word){
            if(!empty($word)){// there are circustances that the user input two or more blank so it will result to a blank result
                $final_search_words[] = $word;


            }
        }
    }



    // Generate a WHERE clause using all of the search keywords
    $where_list = array();
    if(count($final_search_words) > 0){
        foreach($final_search_words as $word){
            $where_list[] = "content Like '%$word%'";
        }
    }
    $where_clause = implode(' OR ', $where_list);

    //Add the keyword WHERE clause to the search query
    if(!empty($where_clause)){
        $search_query .= " WHERE $where_clause";
    }




    // Sort the search query using the sort setting
    switch ($sort) {
        // Ascending by title
        case 1:
            $search_query .= " ORDER BY title";
            break;
        // Desending by title  
        case 2:
            $search_query .= " ORDER BY title DESC";
            break; 

        // Ascending by created_at
        case 3:
            $search_query .= " ORDER BY created_at";
            break;
        // Descending by created_at
        case 4:
            $search_query .= " ORDER BY created_at DESC";
            break;     
        default:
            // No sort setting provided, so don't sort the query
            //break;
    }

    return $search_query;

} //END OF build_query() FUNCTION


// This function builds heading links based on the specified sort setting

function generate_sort_links($user_search, $sort){
    $sort_links = '';

    switch ($sort) {
        case 1:
            $sort_links .= '<li><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=2">Title</a></td><td>Description</li>';
            $sort_links .= '<li><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=4">created_Time</a></td><td>Description</li>';
            break;
        case 3:
            $sort_links .= '<li><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=4">created_Time</a></td><td>Description</li>';
            $sort_links .= '<li><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=2">Title</a></td><td>Description</li>';
            break;

        default:
            $sort_links .= '<li><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=3">created_Time</a></td><td>Description</li>';
    }

    return $sort_links;

}//end of  generate_sort_links




 // This function builds navigational page links based on the current page and the number of pages
function generate_page_links($user_search, $sort, $cur_page, $num_pages) {
    $page_links = '';

    // If this page is not the first page, generate the "previous" link
    if($cur_page >1){
      $page_links .= '<a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . ($cur_page - 1) . '"><-</a> ';
    }else{
        $page_links .= '<- ';
    }

    // Loop through the pages generating the page number links
    //loop through all the pages
    for($i = 1; $i <= $num_pages; $i++){
        if($cur_page == $i){
            $page_links .= ' ' . $i;
            //if current page, get rid of the url
        }else{
            $page_links  .= ' <a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . $i . '"> ' . $i . '</a>';
            //if not current page, add the url to make it point to next page or previous page
        }

    }


    //// If this page is not the last page, generate the "next" link
    if($cur_page < $num_pages){
        $page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . ($cur_page + 1) . '">-></a>';
        //if not last page, make -> have a url and can point to the previous one
    }else{
        $page_links .= ' ->';
    }


    return $page_links;

}//end of generate_page_links function




 // Grab the sort setting and search keywords from the URL using GET

 $sort = $_GET['sort'];
 $user_search = $_GET['usersearch'];

 //// Calculate pagination information
 $cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
 $result_per_page = 5;// number of results per page
 $skip = (($cur_page -1) * $results_per_page);


 // Start generating the search results
 echo '<div class="filter">';
 echo generate_sort_links($user_search, $sort);
 echo '</div>';

 // Connect to the database
  require_once('dbinfo.php');
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);


  // Query to get the total results 
  $query = build_query($user_search, $sort);
  $result = mysqli_query($dbc, $query);

  $total = mysqli_num_rows($result);
  $num_pages = ceil($total / $results_per_page);

  // // Query again to get just the subset of results
  $query = $query . " LIMIT $skip, $results_per_page";
  //limit 10,5 means skip the 10 and return 5  
  //$skip = (($cur_page -1) * $results_per_page);

  $result = mysqli_query($dbc, $query);
  while ($row = mysqli_fetch_array($result)) {
    echo '<div class="search_item">';
    echo '<div>' . $row['title'] . '</div>';
    echo '<div>' . $row['created_at'] . '</div>';
    echo '<div>' . substr($row['content'], 0,300) . '</div>';
    echo '</div>';//end of search_item wrap
  }


   // Generate navigational page links if we have more than one page
  if($num_pages >1 ){
    echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
  }

  mysqli_close($dbc);

2 个答案:

答案 0 :(得分:2)

在这里你可以找到一种简单的方法来进行无限滚动:

JS:

var callback = function test() {

    // Log how the height increases to the console
    console.log(document.getElementById('infinite').style.height)

    // equivalent to $('#infinite') in jQuery
    var el = document.getElementById('infinite');
    var newHeight = document.getElementById('infinite').offsetHeight + 200;

    // Update the height property of the selected element
    el.style.height = newHeight + 'px';
}

window.addEventListener('scroll', callback, false);

基本上添加一个附加到滚动的事件监听器,因此,每次滚动时,该函数都会被触发并增加元素的height属性。

你只需要一个div:

<div id='infinite' style='height: 2000px'></div>

这是fiddle

希望有所帮助:)

答案 1 :(得分:1)

您需要做的是滚动的Ajax调用,它会附加产品。之前已经提出过这个问题并在此处回答:On Scroll down how to make ajax call and get the respone data

当用户到达页面末尾时,代码执行ajax调用。通过跟踪产品数量,您可以使用ajax调用发送偏移量和限制,以便在数据库查询中使用它。

修改 看看我刚发现的东西:http://www.smarttutorials.net/infinite-scroll-using-jquery-ajax-php-and-mysql/如果这没有帮助......

编辑2: 没有wordpress,所以删除了代码