2012-12-12 1 views
5

좋아요. 저는 검색하고 답변을 검색했지만 찾고있는 일반 영역에서는 아직 하나도 찾지 못했습니다. iScroll에 대해 잘 알고 있지 않습니다. (이 프로젝트의 이전 개발자가 그것을 추가 했으므로 이제 끝내고 있습니다.) 저는 iScroll을 어디에서부터 시작해야하는지 알아 내려고 노력하고 있습니다.iScroll lite가 요소의 끝이나 스크롤 바 끝까지 도달했을 때 찾습니다.

지금 당장 모든 항목이 위아래로 스크롤하는대로 작동하는 것으로 보입니다. 하지만 개발 된 전반적인 앱에 이전 데이터를 가져 와서 그 시간에 나열된 최신 데이터에 추가하는 등의 기능을 추가하고 싶습니다. 무한의 두루마리.

아약스를 통해 데이터를 가져 와서 추가하고 iScroll 길이를 새로 고치는 작업은 그리 큰 문제가 아닙니다. 내 문제는 바닥에 도달했을 때 그 순간을 찾아서 데이터를 가져 와서 추가 할 함수를 실행하는 것입니다. 나는이 질문은 꽤 오래 때문에 여기에 누군가가 나에게 몇 가지 아이디어

답변

11

을 던질 수 바라고 있도록

난 아무데도 예제를 찾을 수 없습니다. 이 솔루션은 모든 향후 참조 용입니다.

사용 iScroll의 v4.2.5 : 하루를 따라 후

var scroll = new iScroll('scroll-wrapper'); 
scroll.options.onScrollEnd = function(){ 
    if(Math.abs(this.maxScrollY) - Math.abs(this.y) < 10){ 
     // RUN CODE if scroll is 10px from the bottom. 
    } 
}; 
+0

감사 landing_more.php이라고합니다. onScrollEnd 함수를 생성자에 전달 된 옵션의 일부로 포함 할 수 있습니다. 예 : 새로운 iScroll ('요소', {onScrollEnd : function() {...}); – jackocnr

+0

좋아, 그게 내가 원하는거야. – Xinan

+0

iScroll-Probe와 V5의 줌과 같은 다른 '향수'기능을 사용해야하는 경우에도 사용할 수 있습니다. 이 예제에서는 iScroll-zoom을 사용하여이 이벤트를 사용하여 무한 스크롤을 구성 할 수 있습니다. – StinkyCat

-1

, 난 부드러운 무한 스크롤을 구현 iscroll4 사용하여 샘플 응용 프로그램을 새로 끌어왔다. 이 두 기능은 내가 만든 하나의 샘플 앱에서 구현되었습니다. 이 모바일 앱 개발자 커뮤니티에 유용하게 사용되기를 바랍니다.

  1. 당신이 (중 하나 전문가 필요성의 COS 많이하지하고 있지 않다) iscroll4 기능에 익숙 :

    먼저이 있다고 가정한다.
  2. 당신은 JSON 파일 또는 JSON/PHP 파일에 아약스 호출을 만드는 방법을 알고

내 응용 프로그램 요약 : 사용자가 내 응용 프로그램을로드 할 때

, 그것은 JSON/PHP 파일에에 아약스 호출을 내 서버 및 일부 값이 반환됩니다.

문제의 본질 : 나는 무한 스크롤함께 풀은 기능을 새로 고칠와 나는 iscroll4에서 떨어져 다른 프레임 워크를 사용 싶지 않다.

내 솔루션 :

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> 
<meta name="apple-mobile-web-app-capable" content="yes"> 
<meta name="apple-mobile-web-app-status-bar-style" content="black"> 
<link href="http://fonts.googleapis.com/css?family=Headland+One%7COpen+Sans:400,300&amp;subset=latin,cyrillic" rel="stylesheet" type="text/css"></link> 
    <link href="css/mystylesheet.css" rel="stylesheet"> 
<style> 

/** 
* 
* Horizontal Scrollbar 
* 
*/ 
.myScrollbarH { 
    position:absolute; 
    z-index:100; 
    height:8px; 
    bottom:1px; 
    left:2px; 
    right:7px 
} 

.myScrollbarH > div { 
    position:absolute; 
    z-index:100; 
    height:100%; 

    /* The following is probably what you want to customize */ 
    background:-webkit-gradient(linear, 0 0, 100% 0, from(#226BF4), to(#226B8F)); 
    background-image:-moz-linear-gradient(top, #226BF4, #226B8F); 
    background-image:-o-linear-gradient(top, #226BF4, #226B8F); 

    border:1px solid #226BF4; 

    -webkit-background-clip:padding-box; 
    -moz-background-clip:padding-box; 
    -o-background-clip:padding-box; 
    background-clip:padding-box; 

    -webkit-box-sizing:border-box; 
    -moz-box-sizing:border-box; 
    -o-box-sizing:border-box; 
    box-sizing:border-box; 

    -webkit-border-radius:4px; 
    -moz-border-radius:4px; 
    -o-border-radius:4px; 
    border-radius:4px; 

    -webkit-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5); 
    -moz-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5); 
    -o-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5); 
    box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5); 
} 


/** 
* 
* Vertical Scrollbar 
* 
*/ 
.myScrollbarV { 
    position:absolute; 
    z-index:100; 
    width:8px;bottom:7px;top:2px;right:1px 
} 

.myScrollbarV > div { 
    position:absolute; 
    z-index:100; 
    width:100%; 

    /* The following is probably what you want to customize */ 
    background:-webkit-gradient(linear, 0 0, 100% 0, from(#226BF4), to(#226B8F)); 
    background-image:-moz-linear-gradient(top, #226BF4, #226B8F); 
    background-image:-o-linear-gradient(top, #226BF4, #226B8F); 

    border:1px solid #226BF4; 

    -webkit-background-clip:padding-box; 
    -moz-background-clip:padding-box; 
    -o-background-clip:padding-box; 
    background-clip:padding-box; 

    -webkit-box-sizing:border-box; 
    -moz-box-sizing:border-box; 
    -o-box-sizing:border-box; 
    box-sizing:border-box; 

    -webkit-border-radius:4px; 
    -moz-border-radius:4px; 
    -o-border-radius:4px; 
    border-radius:4px; 

    -webkit-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5); 
    -moz-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5); 
    -o-box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5); 
    box-shadow:inset 1px 1px 0 rgba(255,255,255,0.5); 
} 

/** 
* 
* Pull down styles 
* 
*/ 
#pullDown, #pullUp { 
    background:#fff; 
    height:40px; 
    line-height:40px; 
    padding:5px 10px; 
    border-bottom:1px solid #ccc; 
    font-weight:bold; 
    font-size:14px; 
    color:#888; 
} 
#pullDown .pullDownIcon, #pullUp .pullUpIcon { 
    display:block; float:left; 
    width:40px; height:40px; 
    background:url(images/[email protected]) 0 0 no-repeat; 
    -webkit-background-size:40px 80px; background-size:40px 80px; 
    -webkit-transition-property:-webkit-transform; 
    -webkit-transition-duration:250ms; 
} 
#pullDown .pullDownIcon { 
    -webkit-transform:rotate(0deg) translateZ(0); 
} 
#pullUp .pullUpIcon { 
    -webkit-transform:rotate(-180deg) translateZ(0); 
} 

#pullDown.flip .pullDownIcon { 
    -webkit-transform:rotate(-180deg) translateZ(0); 
} 

#pullUp.flip .pullUpIcon { 
    -webkit-transform:rotate(0deg) translateZ(0); 
} 

#pullDown.loading .pullDownIcon, #pullUp.loading .pullUpIcon { 
    background-position:0 100%; 
    -webkit-transform:rotate(0deg) translateZ(0); 
    -webkit-transition-duration:0ms; 

    -webkit-animation-name:loading; 
    -webkit-animation-duration:2s; 
    -webkit-animation-iteration-count:infinite; 
    -webkit-animation-timing-function:linear; 
} 

@-webkit-keyframes loading { 
    from { -webkit-transform:rotate(0deg) translateZ(0); } 
    to { -webkit-transform:rotate(360deg) translateZ(0); } 
} 

</style> 
</head> 
<body style="overflow: hidden;" onload="do_refresh();"> 
<div class="wrap"> 
<div id="wrapper"> 
     <div id="scroller"> 
     <div id="pullDown"> 
      <span class="pullDownIcon"></span><span class="pullDownLabel">Pull down to refresh...</span> 
     </div> 

    <div class="content"> 
    <input type="hidden" id="last_id">    
      <div id="responsecontainer"></div> 
     </div> 

     <span class="load_more_loading" ></span> 
    </div> 
    </div> 
</div> 


     <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> 
     <script src="js/iscroll.js"></script> 
<script src="js/pulltorefresh.js"></script> 
<script src="js/infinitescroll.js></script> 

<script src="js/myinitialloadscript.js"></script> 
    <script src="js/mymobileframework.js"></script> <!--independent of this script. eg. whormhole from mosync--> 

    </body> 
     </html> 

옆 myinitialloadscript.js 스크립트를 작성하는 것입니다. 이렇게하면 해당 페이지에서 처음으로 콘텐츠를 앱에로드 할 수 있습니다.

function do_refresh() 
    { 


    var url = "http://localhost/public_html/landing.php?token=908765789897867567687989089786768980&validator=jhjhjjhjhkhj"; //just url params 
    // ------------------------------------------- 

    $.ajax({ 
      type: 'GET', 
      url: url, 
      contentType: "application/json; charset=utf-8", 
      dataType: "jsonp", 
      // Evaluate text as a json expression 
      converters: {"text jsonp": jQuery.parseJSON}, 
      timeout:30000, 
      async: true, 
      jsonp: true, 
      jsonpCallback: "myJsonMethod", 
      beforeSend: function() 
      { 


//add loading image i dint bcos the image or values becomes double in a case of network delay 
      $("#responsecontainer").html("images/loader.gif").show(); 
      }, 
      success: function(data) 
      { 
      ajax.parseJSONP(data); 
      }, 
      error: function(jqXHR, textStatus, errorThrown) 
      { 
      console.log(errorThrown); 
      alert("Could Not Refresh."); 
      $("#responsecontainer").html("");//remove loading image 
      //$("#responsecontainer").load("refresh_h.html"); //load a page with refresh option. 
      } 
     }); 
    $.ajaxSetup({ cache: false }); //fetch data from db not cache content 
    } 


//if data is fectched successfully then 

    var ajax = { 

     parseJSONP:function(data){ 



      $.each(data, function(i, row) { 
      if (i==0){ 
      $("#responsecontainer").html(''); 
      } 

      var ul = '<li>'+row.myjsondatakey+'</li>'; //could be <div></div> This only displays your values from db in a styled manner 
      $(ul).appendTo('#responsecontainer');// append the value to the responsecontainer 

//Now watch closely. remember it was assumed you have a json file or json/php file, and in 
//most cases you get your json data format from PHP file. so we assume its from a php file. 
//also note that php calls to db can have a LIMIT. so in this case my PHP file data LIMIT 
//was set to 5. because of infinite scrolling, i need to know the id of the last element 
//from my returned data. so i write the following. note that my row.id_comments which is my 
//value i want to get was written into an input whose visibility is hidden. this is to 
//enable me over write its value when the last id changes. 
      if (i==4) 
      { 
      //set last id value 
      $('#last_id').val(row.id_comments); 
      } 

    }); 
    } 
    } 

다음 iscroll4의 예는 명확하기 때문에 많은 이것에 대해 말할 수 woun't pulltorefresh.js을 구현하는 것입니다.

var myScroll, 
    pullDownEl, pullDownOffset, 
    pullUpEl, pullUpOffset, 
    generatedCount = 0; 

function pullDownAction() { 
     var el; 
     el = document.getElementById('responsecontainer'); 

var url = "http://localhost/public_html/landing.php?token=78654567897654356789976546789&valid=jhjhjjhjhkhj"; 

     $.ajax({ 
     type: 'GET', 
     url: url, 
     contentType: "application/json; charset=utf-8", 
     dataType: "jsonp", 
     // Evaluate text as a json expression 
     converters: {"text jsonp": jQuery.parseJSON}, 
     timeout:30000, 
     async: true, 
     jsonp: true, 
     jsonpCallback: "myJsonMethod", 
     error: function(){ 
     myScroll.refresh(); //do nofin 
     }, 
     success: function(data){ 
     //console.dir('success'); 
     ajax.parseJSONP(data); 
     } 
     }); 
$.ajaxSetup({ cache: false }); //fetch data from db not cache content 


var ajax = { 

    parseJSONP:function(data){ 
     $.each(data, function(i, row) { 

     if (i==0){ 
     $("#responsecontainer").html(''); 
     } 

     var ul = '<li>'+row.myjsondatakey+'</li>'; 
     $(ul).appendTo(el); 


if (i==4) 
      { 
      //set last id value 
      $('#last_id').val(row.id_comments); 
      } 
     myScroll.refresh(); // Remember to refresh when contents are loaded (ie: on ajax completion) 

}); 
} 
} 
} 



    function loaded() { 
     pullDownEl = document.getElementById('pullDown'); 
     pullDownOffset = pullDownEl.offsetHeight; 

     myScroll = new iScroll('wrapper', { 
      scrollbarClass: 'myScrollbar', 
      useTransition: true, 
      topOffset: pullDownOffset, 
      onRefresh: function() { 
       if (pullDownEl.className.match('loading')) { 
        pullDownEl.className = ''; 
        pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...'; 
       } 
      }, 
      onScrollMove: function() { 
       if (this.y > 5 && !pullDownEl.className.match('flip')) { 
        pullDownEl.className = 'flip'; 
        pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Release to refresh...'; 
        this.minScrollY = 0; 
       } else if (this.y < 5 && pullDownEl.className.match('flip')) { 
        pullDownEl.className = ''; 
        pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...'; 
        this.minScrollY = -pullDownOffset; 
       } 
      }, 

//here is where infinite scroll comes in 
       onScrollEnd: function() { 
       //infinite scroll started 
       if(Math.abs(this.maxScrollY) - Math.abs(this.y) < 10) 
       { 
       // Do infinite if scroll is 10px from the bottom. 
       doInfinite_scroll(); 
       } 

       //infinite scroll ended 

       if (pullDownEl.className.match('flip')) { 
        pullDownEl.className = 'loading'; 
        pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Loading...';     
        pullDownAction(); // Execute custom function (ajax call?) 
       } 
      } 
     }); 

     setTimeout(function() { document.getElementById('wrapper').style.left = '0'; }, 800); 
    } 


    document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); 

    document.addEventListener('DOMContentLoaded', function() { setTimeout(loaded, 200); }, false); 

와 마지막으로 주요 infinitescroll.js 우리가 스크롤 막대가 inifite 스크롤이 트리거해야 끝에 10px 경우 우리가 말했다 pulltorefresh.js에서이 함수에 대한 호출을 배치 이전에했던 것을 기억하지 않는 이상.그런 다음 우리는 이것을 해고 할 총격으로 사용합니다.

function doInfinite_scroll() 
{ 
     var last_id = $('#last_id').val(); 
     var searching = false; 
     if (!searching) { // only initiate a new ajax request if this variable is false this is to avoid data duplication. 
     var el; 
     el = document.getElementById('responsecontainer'); 
     var url = "http://localhost/public_html/landing_more.php?last_id="+last_id+"&token=9876543456789765432456789876543&valid=jhjhjjhjhkhj"; 
     // ------------------------------------------- 

     $.ajax({ 
     type: 'GET', 
     url: url, 
     contentType: "application/json; charset=utf-8", 
     dataType: "jsonp", 
     // Evaluate text as a json expression 
     converters: {"text jsonp": jQuery.parseJSON}, 
     timeout:30000, 
     async: true, 
     jsonp: true, 
     jsonpCallback: "myJsonMethod", 
     error: function(){ 
     myScroll.refresh(); //do nofin 
     }, 
     beforeSend: function() 
     { 
     //add loading image i dint bcos the image or values becomes double in a case of network delay 
     searching = true; // set variable to true 
     }, 
     success: function(data){ 
     searching = false; // set variable to false 
     //console.dir('success'); 
     ajax.parseJSONP(data); 

     } 
     }); 
     $.ajaxSetup({ cache: false });//fetch data from db not cache content 
     var ajax = { 

     parseJSONP:function(data){ 
     $.each(data, function(i, row) { 


     var ul = '<ul>'+row.comments+'</ul>'; 
     if (i==1) //bcos its php data limit was set to 2 so its always N-1 i.e yourlimit - 1 
     { 
     //resset lastdeed id value 
     $('#lastdeed_id').val(row.id_comments); //update the value in the hidden input field to enable the next set of data load properly 
     } 
     $(ul).appendTo(el); 
     myScroll.refresh();  // Remember to refresh when contents are loaded (ie: on ajax completion) 

}); 
} 
} 
} 
} 

PHP 파일이 여기에 표시되어야하는 것과 관련하여 분실 한 경우를 대비하여. 이 파일은 다음의 파일이 무한 스크롤입니다 landing.php

<?php 
// Prevent caching. 
header('Cache-Control: no-cache, must-revalidate'); 
header('Expires: Mon, 01 Jan 1996 00:00:00 GMT'); 

if ((isset($_GET['token'])) && (isset($_GET['valid']))) { 

@require_once('connect/connectionfile.php'); 

$token=htmlspecialchars($_GET['token'],ENT_QUOTES); 
$token= mysql_real_escape_string($token); 
$valid=htmlspecialchars($_GET['valid'],ENT_QUOTES); 
$valid= mysql_real_escape_string($valid); 


//now validating the token 
$sql="SELECT * FROM bla WHERE blabla='$token'"; 
$result=mysql_query($sql); 

//if token exists 
if(mysql_num_rows($result)) 
{ 
header('Content-type: application/json'); 
//valid token 
$fakevalue = mysql_fetch_assoc($result); 
$uid = $fakevalue['id']; 
$results = array(); 
$query = "SELECT * FROM bla bal WHERE bla bla bla DESC LIMIT 0, 5"; 
$rsult = mysql_query($query); 
while($value = mysql_fetch_assoc($rsult, MYSQL_ASSOC)) 
$results[] = $value; 
{ 
echo "myJsonMethod".'('.json_encode($results).')'; //ECHO RESULTS IN JSONP FORMAT 

} 

} 
else 
{ 
//Invalid token 
header('Content-type: application/json'); 
echo "myJsonMethod({\"token\":".utf8_encode(json_encode('failed'))."})"; 
} 
} 
else { 
    header('Content-type: application/json'); 
    echo "myJsonMethod({\"token\":".utf8_encode(json_encode('Invalid token check parameters'))."})"; 
    } 
?> 

이며

<?php 
// Prevent caching. 
header('Cache-Control: no-cache, must-revalidate'); 
header('Expires: Mon, 01 Jan 1996 00:00:00 GMT'); 

if ((isset($_GET['token'])) && (isset($_GET['validator']))) { 

@require_once('connect/connectionfile.php'); 


$token=htmlspecialchars($_GET['token'],ENT_QUOTES); 
$token= mysql_real_escape_string($token); 
$validator=htmlspecialchars($_GET['validator'],ENT_QUOTES); 
$validator= mysql_real_escape_string($validator); 
$last_id=htmlspecialchars($_GET['last_id'],ENT_QUOTES); 
$last_id=mysql_real_escape_string($last_id); 


//now validating the token 
$sql="SELECT * FROM bla WHERE blabla='$token'"; 
$result=mysql_query($sql); 

//if token exists 
if(mysql_num_rows($result)) 
{ 
header('Content-type: application/json'); 
//valid token 
$fakevalue = mysql_fetch_assoc($result); 
$uid = $fakevalue['id']; 
$results = array(); 
$query = "SELECT * FROM bla bla WHERE bla && bla bla && a.id_comments < '$last_id' ORDER BY a.id_comments DESC LIMIT 0, 2"; 
$rsult = mysql_query($query); 
while($value = mysql_fetch_assoc($rsult, MYSQL_ASSOC)) 
$results[] = $value; 
{ 
echo "myJsonMethod".'('.json_encode($results).')'; //ECHO RESULTS IN JSONP FORMAT 

} 

} 
else 
{ 
//Invalid token 
header('Content-type: application/json'); 
echo "myJsonMethod({\"token\":".utf8_encode(json_encode('failed'))."})"; 
} 
} 
else { 
    header('Content-type: application/json'); 
    echo "myJsonMethod({\"token\":".utf8_encode(json_encode('Invalid token check parameters'))."})"; 
    } 
?> 
관련 문제