2011-03-14 20 views
6

Estoy usando padilicious para detectar gestos de deslizamiento para páginas web que se verán en iOS y computadoras de escritorio. Funciona muy bien deslizar hacia la izquierda/derecha para las páginas anteriores y siguientes de mi sitio. Sin embargo, parece anular el comportamiento predeterminado en iPhone/iPad al deslizar hacia arriba/abajo. Me gustaría un deslizamiento hacia arriba o hacia abajo para desplazar la página, que es lo que hace cuando no tengo una ejecución padilicious. Simplemente haciendo que el código ignore los deslizadores arriba/abajo no parece funcionar.Agregue deslizar hacia la izquierda/derecha a la página web, pero use la función predeterminada deslizar hacia arriba/abajo

La sección de código padilicious que he estado

function processingRoutine() { 
    var swipedElement = document.getElementById(triggerElementID); 
    if (swipeDirection == 'left') { 
     document.location = document.getElementById('nextPage').href; 
    } else if (swipeDirection == 'right') { 
     document.location = document.getElementById('prevPage').href; 
    } else if (swipeDirection == 'up') { 
     return; 
    } else if (swipeDirection == 'down') { 
     return; 
    } 


} 

Respuesta

5

Elimina event.preventDefault(); de entre todas las funciones. En la función processingRoutine() {}, agregue event.preventDefault(); para lo que desee.

function processingRoutine() { 
    var swipedElement = document.getElementById(triggerElementID); 
    if (swipeDirection == 'left') { 
     // REPLACE WITH YOUR ROUTINES 
     //swipedElement.style.backgroundColor = 'orange'; 
     event.preventDefault(); 
    } else if (swipeDirection == 'right') { 
     // REPLACE WITH YOUR ROUTINES 
     //swipedElement.style.backgroundColor = 'green'; 
     event.preventDefault(); 
    } else if (swipeDirection == 'up') { 
     // REPLACE WITH YOUR ROUTINES 
     //swipedElement.style.backgroundColor = 'maroon'; 
    } else if (swipeDirection == 'down') { 
     // REPLACE WITH YOUR ROUTINES 
     //swipedElement.style.backgroundColor = 'purple'; 
    } 
} 
+0

¡Impresionante, gracias! –

+0

Esto funciona en el navegador de acciones de Android y en Firefox, pero no en google chrome. Tenga en cuenta también: se debe pasar el evento. –

1

no estoy familiarizado con padilicious, pero comprobar y ver si el ontouchmove="BlockMove(event);" se fija en cualquier lugar, que impide que la página de desplazamiento como usted describe, No estoy seguro de cómo conseguirlo para mantener el desplazamiento vertical, sino deslizar horizontalmente.

Editar: Desde entonces, encontré una visión muy útil para hacer aplicaciones web de iOS "nativas", puede que no sea exactamente lo que está buscando, pero podría proporcionarle otra vía de acercamiento a su problema. Compruébelo usted mismo: http://matt.might.net/articles/how-to-native-iphone-ipad-apps-in-javascript/

+0

El código no incluye 'BlockMove (evento)' Pero me alegro de saber acerca de eso, gracias. –

+0

Desde entonces he encontrado un enlace que puede ser útil, editado en mi respuesta anterior. –

+0

¡Gracias! El código es interesante: 'var IsiPhone = navigator.userAgent.indexOf (" iPhone ")! = -1; var IsiPod = navigator.userAgent.indexOf ("iPod")! = -1; var IsiPad = navigator.userAgent.indexOf ("iPad")! = -1; var IsiPhoneOS = IsiPhone || IsiPad || IsiPod; ' –

2

hay una biblioteca de jQuery, que hace el trabajo (al no proporcionar a los métodos/abajo): http://plugins.jquery.com/project/Touchwipe-iPhone-iPad-wipe-gesture

+0

gracias, esto parece una buena opción de jquery para deslizar. Sin embargo, tiene los mismos problemas. Ver http://www.netcu.de/jquery-touchwipe-iphone-ipad-library. Deslizar hacia la izquierda/derecha en el divisor de imagen cambia la imagen, pero deslizar hacia arriba/abajo no hace nada, incluido el desplazamiento. Me gustaría poder desplazarme cuando alguien desliza hacia arriba o hacia abajo en el contenido div de mi sitio, y pasar al siguiente/atrás al deslizar hacia la izquierda/derecha. Deslizar fuera del contenido div funciona bien (comportamiento predeterminado). –

1

Padilicious parece estar impidiendo por defecto en todos los casos. Ver la llamada a event.preventDefault() en todos los casos.

function touchStart(event,passedName) { 
    // disable the standard ability to select the touched object 
    event.preventDefault(); 

Tendrá que cambiar de marcha, paro, ... manipuladores de no llamar a preventDefault() en los casos arriba y hacia abajo.

0

me cambió el guión, esta obra:

// TOUCH-EVENTS SINGLE-FINGER SWIPE-SENSING JAVASCRIPT 
// Courtesy of PADILICIOUS.COM and MACOSXAUTOMATION.COM 

// this script can be used with one or more page elements to perform actions based on them being swiped with a single finger 

var triggerElementID = null; // this variable is used to identity the triggering element 
var fingerCount = 0; 
var startX = 0; 
var startY = 0; 
var curX = 0; 
var curY = 0; 
var deltaX = 0; 
var deltaY = 0; 
var horzDiff = 0; 
var vertDiff = 0; 
var minLength = 72; // the shortest distance the user may swipe 
var swipeLength = 0; 
var swipeAngle = null; 
var swipeDirection = null; 

// The 4 Touch Event Handlers 

// NOTE: the touchStart handler should also receive the ID of the triggering element 
// make sure its ID is passed in the event call placed in the element declaration, like: 
// <div id="picture-frame" ontouchstart="touchStart(event,'picture-frame');" ontouchend="touchEnd(event);" ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);"> 

function touchStart(event,passedName) { 
    // disable the standard ability to select the touched object 
    //event.preventDefault(); 
    // get the total number of fingers touching the screen 
    fingerCount = event.touches.length; 
    // since we're looking for a swipe (single finger) and not a gesture (multiple fingers), 
    // check that only one finger was used 
    if (fingerCount == 1) { 
     // get the coordinates of the touch 
     startX = event.touches[0].pageX; 
     startY = event.touches[0].pageY; 
     // store the triggering element ID 
     triggerElementID = passedName; 
    } else { 
     // more than one finger touched so cancel 
     touchCancel(event); 
    } 
} 

function touchMove(event) { 
    //event.preventDefault(); 
    if (event.touches.length == 1) { 
     curX = event.touches[0].pageX; 
     curY = event.touches[0].pageY; 
    } else { 
     touchCancel(event); 
    } 
} 

function touchEnd(event) { 
    //event.preventDefault(); 
    // check to see if more than one finger was used and that there is an ending coordinate 
    if (fingerCount == 1 && curX != 0) { 
     // use the Distance Formula to determine the length of the swipe 
     swipeLength = Math.round(Math.sqrt(Math.pow(curX - startX,2) + Math.pow(curY - startY,2))); 
     // if the user swiped more than the minimum length, perform the appropriate action 
     if (swipeLength >= minLength) { 
      caluculateAngle(); 
      determineSwipeDirection(); 
      processingRoutine(); 
      touchCancel(event); // reset the variables 
     } else { 
      touchCancel(event); 
     } 
    } else { 
     touchCancel(event); 
    } 
} 

function touchCancel(event) { 
    // reset the variables back to default values 
    fingerCount = 0; 
    startX = 0; 
    startY = 0; 
    curX = 0; 
    curY = 0; 
    deltaX = 0; 
    deltaY = 0; 
    horzDiff = 0; 
    vertDiff = 0; 
    swipeLength = 0; 
    swipeAngle = null; 
    swipeDirection = null; 
    triggerElementID = null; 
} 

function caluculateAngle() { 
    var X = startX-curX; 
    var Y = curY-startY; 
    var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels 
    var r = Math.atan2(Y,X); //angle in radians (Cartesian system) 
    swipeAngle = Math.round(r*180/Math.PI); //angle in degrees 
    if (swipeAngle < 0) { swipeAngle = 360 - Math.abs(swipeAngle); } 
} 

function determineSwipeDirection() { 
    if ((swipeAngle <= 45) && (swipeAngle >= 0)) { 
     swipeDirection = 'left'; 
    } else if ((swipeAngle <= 360) && (swipeAngle >= 315)) { 
     swipeDirection = 'left'; 
    } else if ((swipeAngle >= 135) && (swipeAngle <= 225)) { 
     swipeDirection = 'right'; 
    } 

    /* else if ((swipeAngle > 45) && (swipeAngle < 135)) { 
     swipeDirection = 'down'; 
    } else { 
     swipeDirection = 'up'; 
    }*/ 
} 

function processingRoutine() { 
    var swipedElement = document.getElementById(triggerElementID); 
    if (swipeDirection == 'left') { 
     // REPLACE WITH YOUR ROUTINES 
     event.preventDefault(); 
     swipedElement.style.backgroundColor = 'orange'; 
    } else if (swipeDirection == 'right') { 
     // REPLACE WITH YOUR ROUTINES 
     event.preventDefault(); 
     swipedElement.style.backgroundColor = 'green'; 
    } 

    /*else if (swipeDirection == 'up') { 
     // REPLACE WITH YOUR ROUTINES 
     swipedElement.style.backgroundColor = 'maroon'; 
    } else if (swipeDirection == 'down') { 
     // REPLACE WITH YOUR ROUTINES 
     swipedElement.style.backgroundColor = 'purple'; 
    }*/ 
} 
+1

esto ya no funcionará, ya que nunca detectará el deslizamiento en primer lugar. – ojsglobal

Cuestiones relacionadas