OK Ive tenía con este script! jQuery cuestión de arrastre!

  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 260
  • Status: Offline

Nota Enero 31st, 2013, 9:30 am

Im sobre listo para zanjar esto todos juntos y encontrar una ruta diferente. En primer lugar el sitio Im aplicando esto a no se construyó con el uso intencionado de jQuery pero la característica que tengo que añadir jQuery sería perfecto para. De hecho ya es configuración y trabajando sin embargo Im habiendo un infierno de una vez con la fricción. El sitio es una intranet acceso denegado . El proyecto es una imagen de archivo sistema su base sobre un árbol de archivos y la función que desean agregar para arrastrar las imágenes a otras carpetas. Todo se carga a través de AJAX y cuando se cargue la carpeta que contiene la imagen simplemente puse una clase de arrastrable en el div contenedor una vez recupero la do de petición AJAX esto.
JAVASCRIPT Código: [ Select ]
$(function() {
    $('.draggable').draggable({
        opacity: 0.5,
        revert: true,
        cursorAt: {
            top: 8,
            left: -8
        },
        helper: function( event ) {
            return $('<img src="http://archive.mysite.com/aia/new_site/images/fam/photo_add.png">');
        }
    });
});
 
  1. $(function() {
  2.     $('.draggable').draggable({
  3.         opacity: 0.5,
  4.         revert: true,
  5.         cursorAt: {
  6.             top: 8,
  7.             left: -8
  8.         },
  9.         helper: function( event ) {
  10.             return $('<img src="http://archive.mysite.com/aia/new_site/images/fam/photo_add.png">');
  11.         }
  12.     });
  13. });
  14.  


OK así que como pueden ver hay nada malo con este, derecho. Ahora llegar a la cuestión han Im viene a tiempo. Cuando usted haga clic y mantenga en el elemento para arrastrar en firefox tarda media (14 veces probado) función 107.1428571428571 milisegundos para llamar a la función de inicio y 985.8571428571429 milisegundos para llamar el arrastre (para empezar a arrastrar). Así de y Ctrl en firefox se tarda aproximadamente un segundo.

Ahora para la pesadilla que debe tener el lugar de para que trabajo las cosas trabajando en IE las otras personas en la empresa no son incluso capaces de instalar cualquier otro browser / permitido.

Misma prueba tarda IE un promedio 135 milisegundos (otra vez 14 pruebas) llamar al comienzo...no esta mal casi lo mismo que Firefox y...3404.428571428571 milisegundos para llamar a arrastrar...casi 3 y un medio segundos. ¿De veras? ¿Alguien tiene alguna idea en absoluto?

Más problemas resolver yo mismo y como siempre voy a publicar cualquier encuentro de soluciones.


Sé más mi post son temas complejos de la IE que chupar pero ayuda sería gran Ive sido meterse con este problema durante un día y medio hasta ahora. Todavía tengo que encontrar a alguien que tiene un problema como éste. Yo sólo pensaba es que hay demasiados elementos html en la página y para algunos jquery razón quiere mirarlas. Es sólo un pensamiento porque solamente construir un objeto arrastrable en IE funciona bien con ninguna demora.
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Enero 31st, 2013, 9:30 am

  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 260
  • Status: Offline

Nota Enero 31st, 2013, 1:05 pm

Pédale. Creo que yo puedo han hallado una solución a mi problema personal en esto arrastrando la cosa sin embargo no está utilizando la función de arrastrar a todos.

Realmente no me gusta trabajar en mis viejos proyectos y mi viejo código realmente me muestra cuánto Ive realmente siento que esto es un truco para solucionar un problema y, bueno, es mejor. Im fuera del tiempo hoy y este fin de semana y no estará en línea excepto tal vez por teléfono hasta el martes. Mal estar en el trabajo de mamut...en mi talla lol. Si alguien tiene alguna idea por favor amor Id escucharlos.

Puaj sólo miré el código otra vez...tan Hacky
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 260
  • Status: Offline

Nota Enero 31st, 2013, 1:16 pm

Hmmmm. Me encontré solo con esto que mal puesta a punto más tarde para ver si funciona mejor. ya que es un widget de arrastre de peso ligero.

http://css-tricks.com/snippets/jquery/d ... jquery-ui/
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 260
  • Status: Offline

Nota Febrero 5th, 2013, 10:22 am

Así que intenté el peso ligero arrastre widget encontré y funciona pero en mi caso es muy nervioso por lo que seguí con mi hack y salió con esto que en mi caso funciona realmente bien, pero probablemente no ayudarán otros.

JAVASCRIPT Código: [ Select ]
$(function() {
   
    // Setup some herlper vars. Moving image will state if we are dragging verse just clicking an image
    // and dragger_id will hold onto the image id we are dragging
    var moving_image = false;  
    var dragger_id;
   
    // Bind the dragstart to not drag anything. I know this sounds strange but we don't want to actually drag anything
    // with the class name of draggable
    $('.draggable').bind('dragstart', function(event) {
       
        // Stop the default action
        event.preventDefault();
   
    });
   
    // Setup the mousedown function on the draggable class name
    $(".draggable").mousedown(function(event) {
                                       
        // Get and set the images id in the dragger id variable
        dragger_id = $(event.target).get(0).id;
       
        // Stop the default action of the mouse down this will prevent the script from firing the
        // default action of just clicking on the image.
        event.preventDefault();
       
        // Setup the mouse move function this will mimic the dragging action
        $(document).mousemove(function(event){
           
            // Check to see if we are moving the image yet. if not and you have been following along.
            // to get here the mouse must be down and you must have moved the mouse.
            if(!moving_image) {
               
                // Make the helper image this is going to be the visual dragging refrence.
                var img
                img = $('<img src="images/fam/photo_add.png">');
                img.attr('id', 'whatADrag');
                img.appendTo('body');
               
            }
           
            // Set the moving image flag to true
            moving_image = true;
           
            // Build the cssobject to position the dragg helper next to the cursor
            var cssObj = {
                'display' : 'inline',
                'position': 'absolute',
                'left' : (event.pageX + 8 ) + 'px',
                'top' : event.pageY +'px'
            };
           
            // Apply the css to the helper
            $("#whatADrag").css(cssObj);
         
        });
   
    });
         
    // Set mouse up event we wat this to be able to fire every where
    $(document).mouseup(function(event) {
                                 
        // Get rid of the help object                
        $("#whatADrag").remove();
       
        // This is created in the mouseover function it is a visual refrence for the folder to drop the file into.
        // we need to remove the te,pdrop image and the class that was applied
        $("#temp_drop").remove();
        $(event.target).removeClass('move-file');
       
        // Make sure we are moving the image before we do anything
        if(moving_image) {
           
            // Set the moving image flag to false so that we no longer do anything with moving the image after exiting this function
            moving_image = false;
           
            // Unbind the mousemove instance
            $(document).unbind('mousemove');
           
            // Check for our drop zones. there are two of them at the current time
            if($(event.target).hasClass('droppable') || $(event.target).hasClass('droppable2')) {
               
                // Get the taget id and remove the string info
                var target_id = $(event.target).get(0).id.replace('node_a_tag_', '');
               
                // Call the function to move the file
                move_file(parseInt(dragger_id), parseInt(target_id));
               
               
               
            }
           
        }
 
    });
           
    // Setup the mouse over and out functions
    $(".droppable, .droppable2").mouseover(function(event){
       
        // Make sure we are moving the image
        if(moving_image) {
           
            // Add the move-file class
            $(this).addClass('move-file');
           
            // Check for the folder and not the tree
            if($(this).hasClass('droppable2')) {
               
                // Make the image add bullet to add a visual refrence to the folder
                var img = $('<img id="temp_drop" src="images/fam/add.png">');
               
                // Check browser type
                if(document.all){
                   
                    // Fix offset position
                    indicator_offset_x = $(this).width() - 16;
                    indicator_offset_y = $(this).height() -16;
                   
                } else if(navigator.userAgent.indexOf('Opera')>=0){
                   
                    // Fix offset position
                    indicator_offset_x = $(this).width() - 16;
                    indicator_offset_y = $(this).height() - 16;                
                   
                } else {
                       
                    // Fix offset position
                    indicator_offset_x = $(this).width() - 16;
                    indicator_offset_y = $(this).height() - 16;
                   
                }
               
            } else {
               
                // Make the image add bullet to add a visual refrence to the folder
                var img = $('<img id="temp_drop" src="images/fam/bullet_add.png">');
               
                // Check browser type
                if(document.all){
                   
                    // Fix offset position
                    indicator_offset_x = -13;
                    indicator_offset_y = 0;
                   
                } else if(navigator.userAgent.indexOf('Opera')>=0){
                   
                    // Fix offset position
                    indicator_offset_x = -13;
                    indicator_offset_y = -5;                
                   
                } else {
                   
                    // Fix offset position
                    indicator_offset_x = -13;
                    indicator_offset_y = 0;            
               
                }
               
            }
               
            // Append to the body of the dom and the display none to stop scrollbar issues
            img.attr('style', 'display:none;');
            img.appendTo('body');
           
            // Make an css Object to postion the image correctly
            var cssObj = {
                'position' : 'absolute',
                'display' : 'inline',
                'left' : ($(this).position().left + indicator_offset_x) +'px',
                'top' : ($(this).position().top + indicator_offset_y) +'px'
            };
           
            // Apply the CSS
            $("#temp_drop").css(cssObj);
           
        }
       
    }).mouseout(function(event){
               
            // Remove the class move-file and the temp drop image
            $(this).removeClass('move-file');
            $("#temp_drop").remove();
               
    });
               
 
});
 
  1. $(function() {
  2.    
  3.     // Setup some herlper vars. Moving image will state if we are dragging verse just clicking an image
  4.     // and dragger_id will hold onto the image id we are dragging
  5.     var moving_image = false;  
  6.     var dragger_id;
  7.    
  8.     // Bind the dragstart to not drag anything. I know this sounds strange but we don't want to actually drag anything
  9.     // with the class name of draggable
  10.     $('.draggable').bind('dragstart', function(event) {
  11.        
  12.         // Stop the default action
  13.         event.preventDefault();
  14.    
  15.     });
  16.    
  17.     // Setup the mousedown function on the draggable class name
  18.     $(".draggable").mousedown(function(event) {
  19.                                        
  20.         // Get and set the images id in the dragger id variable
  21.         dragger_id = $(event.target).get(0).id;
  22.        
  23.         // Stop the default action of the mouse down this will prevent the script from firing the
  24.         // default action of just clicking on the image.
  25.         event.preventDefault();
  26.        
  27.         // Setup the mouse move function this will mimic the dragging action
  28.         $(document).mousemove(function(event){
  29.            
  30.             // Check to see if we are moving the image yet. if not and you have been following along.
  31.             // to get here the mouse must be down and you must have moved the mouse.
  32.             if(!moving_image) {
  33.                
  34.                 // Make the helper image this is going to be the visual dragging refrence.
  35.                 var img
  36.                 img = $('<img src="images/fam/photo_add.png">');
  37.                 img.attr('id', 'whatADrag');
  38.                 img.appendTo('body');
  39.                
  40.             }
  41.            
  42.             // Set the moving image flag to true
  43.             moving_image = true;
  44.            
  45.             // Build the cssobject to position the dragg helper next to the cursor
  46.             var cssObj = {
  47.                 'display' : 'inline',
  48.                 'position': 'absolute',
  49.                 'left' : (event.pageX + 8 ) + 'px',
  50.                 'top' : event.pageY +'px'
  51.             };
  52.            
  53.             // Apply the css to the helper
  54.             $("#whatADrag").css(cssObj);
  55.          
  56.         });
  57.    
  58.     });
  59.          
  60.     // Set mouse up event we wat this to be able to fire every where
  61.     $(document).mouseup(function(event) {
  62.                                  
  63.         // Get rid of the help object                
  64.         $("#whatADrag").remove();
  65.        
  66.         // This is created in the mouseover function it is a visual refrence for the folder to drop the file into.
  67.         // we need to remove the te,pdrop image and the class that was applied
  68.         $("#temp_drop").remove();
  69.         $(event.target).removeClass('move-file');
  70.        
  71.         // Make sure we are moving the image before we do anything
  72.         if(moving_image) {
  73.            
  74.             // Set the moving image flag to false so that we no longer do anything with moving the image after exiting this function
  75.             moving_image = false;
  76.            
  77.             // Unbind the mousemove instance
  78.             $(document).unbind('mousemove');
  79.            
  80.             // Check for our drop zones. there are two of them at the current time
  81.             if($(event.target).hasClass('droppable') || $(event.target).hasClass('droppable2')) {
  82.                
  83.                 // Get the taget id and remove the string info
  84.                 var target_id = $(event.target).get(0).id.replace('node_a_tag_', '');
  85.                
  86.                 // Call the function to move the file
  87.                 move_file(parseInt(dragger_id), parseInt(target_id));
  88.                
  89.                
  90.                
  91.             }
  92.            
  93.         }
  94.  
  95.     });
  96.            
  97.     // Setup the mouse over and out functions
  98.     $(".droppable, .droppable2").mouseover(function(event){
  99.        
  100.         // Make sure we are moving the image
  101.         if(moving_image) {
  102.            
  103.             // Add the move-file class
  104.             $(this).addClass('move-file');
  105.            
  106.             // Check for the folder and not the tree
  107.             if($(this).hasClass('droppable2')) {
  108.                
  109.                 // Make the image add bullet to add a visual refrence to the folder
  110.                 var img = $('<img id="temp_drop" src="images/fam/add.png">');
  111.                
  112.                 // Check browser type
  113.                 if(document.all){
  114.                    
  115.                     // Fix offset position
  116.                     indicator_offset_x = $(this).width() - 16;
  117.                     indicator_offset_y = $(this).height() -16;
  118.                    
  119.                 } else if(navigator.userAgent.indexOf('Opera')>=0){
  120.                    
  121.                     // Fix offset position
  122.                     indicator_offset_x = $(this).width() - 16;
  123.                     indicator_offset_y = $(this).height() - 16;                
  124.                    
  125.                 } else {
  126.                        
  127.                     // Fix offset position
  128.                     indicator_offset_x = $(this).width() - 16;
  129.                     indicator_offset_y = $(this).height() - 16;
  130.                    
  131.                 }
  132.                
  133.             } else {
  134.                
  135.                 // Make the image add bullet to add a visual refrence to the folder
  136.                 var img = $('<img id="temp_drop" src="images/fam/bullet_add.png">');
  137.                
  138.                 // Check browser type
  139.                 if(document.all){
  140.                    
  141.                     // Fix offset position
  142.                     indicator_offset_x = -13;
  143.                     indicator_offset_y = 0;
  144.                    
  145.                 } else if(navigator.userAgent.indexOf('Opera')>=0){
  146.                    
  147.                     // Fix offset position
  148.                     indicator_offset_x = -13;
  149.                     indicator_offset_y = -5;                
  150.                    
  151.                 } else {
  152.                    
  153.                     // Fix offset position
  154.                     indicator_offset_x = -13;
  155.                     indicator_offset_y = 0;            
  156.                
  157.                 }
  158.                
  159.             }
  160.                
  161.             // Append to the body of the dom and the display none to stop scrollbar issues
  162.             img.attr('style', 'display:none;');
  163.             img.appendTo('body');
  164.            
  165.             // Make an css Object to postion the image correctly
  166.             var cssObj = {
  167.                 'position' : 'absolute',
  168.                 'display' : 'inline',
  169.                 'left' : ($(this).position().left + indicator_offset_x) +'px',
  170.                 'top' : ($(this).position().top + indicator_offset_y) +'px'
  171.             };
  172.            
  173.             // Apply the CSS
  174.             $("#temp_drop").css(cssObj);
  175.            
  176.         }
  177.        
  178.     }).mouseout(function(event){
  179.                
  180.             // Remove the class move-file and the temp drop image
  181.             $(this).removeClass('move-file');
  182.             $("#temp_drop").remove();
  183.                
  184.     });
  185.                
  186.  
  187. });
  188.  


El concepto que arrastra nada, pero cuando el ratón hacia abajo en el recipiente de la imagen y luego mover el ratón significa que desea arrastrar para que obtener algo de información en mi caso la identificación de imágenes y crea y agrega una imagen al DOM que sigue el ratón hasta que suelte el botón del ratón, esto dará la parecen que está arrastrando algo cuando tu no. Cuando usted suelta del ratón puede comprobar tus puntos de caída y Obtén más información en mi caso el id de la carpeta de la nueva carpeta para mover el archivo a.
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 8921
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Nota Febrero 5th, 2013, 11:34 am

Es realmente difícil para ayudarle a diagnosticar esto sin verlo en acción, pero se lanzo algunas ideas hacia fuera para ver si eso podría implicar en cualquier lugar.

Lo primero que pensé es que su DOM es realmente grande. En lugar de utilizar un selector de clase amplia como .draggable, has pensado lo enangostar abajo algo como #elemento, o algo más específico.

¿Mi segundo pensamiento es que es posible que tenga una clase pueden arrastrarse dentro de clase pueden arrastrarse? Podría causar problemas también.

Sería curioso cómo a menudo esta función es llamada cuando usted intenta y arrastre el objeto. Tal vez lanzar una alerta allí para ver si se se llama una vez, o miles de veces que harían parecen entrecortada, saltona y retrasada.
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 260
  • Status: Offline

Nota Febrero 5th, 2013, 12:06 pm

Me doy cuenta que es difícil de diagnosticar con a verlo es una acción que intentan proporcionar tanta información como pueda. Más las cosas que hago son en una intranet, así que a menos que en la LAN no son accesibles.

Su primer pensamiento es correcto el DOM es muy grande y también tuve que pensaba y le asigna a cada elemento arrastrable su propio id personalizado y todavía tiene el mismo problema. También dio un paso más allá y hecho un div estático duro codificado en HTML y todavía tenía el retraso en que la secuencia de comandos entrecortado pasa a ser la que peso ligero arrastre widget. No pruebo que fuera para ver cómo a menudo se llama la función está en la escritura de la luz pero en el jQuery ui arrastrable se llama una vez cada vez que se mueve el ratón no tiene un movimiento de la cuestión, pero el retraso se convierte más el elemento más allí que se establecen para ser arrastrables ID individual o un selector de clase amplia.

HTML Código: [ Select ]
<!-- Page html javascript and css above -->
<style type="text/css">
.dragging-box-with-no-possibility-of-duplicating-style {
    width: 100px;
    height: 100px;
    border: 1px solid #000000;
    background-color:#CCCCCC;
    position:absolute;
}
</style>
 
<div id="div_with_an_id_with_no_possibility_of_duplicating" class="dragging-box-with-no-possibility-of-duplicating-style">
Drag Me
</div>
 
<script type="text/javascript">
 
$(function() {
   
   $("#div_with_an_id_with_no_possibility_of_duplicating").draggable();
 
});
 
</script>
 
 
  1. <!-- Page html javascript and css above -->
  2. <style type="text/css">
  3. .dragging-box-with-no-possibility-of-duplicating-style {
  4.     width: 100px;
  5.     height: 100px;
  6.     border: 1px solid #000000;
  7.     background-color:#CCCCCC;
  8.     position:absolute;
  9. }
  10. </style>
  11.  
  12. <div id="div_with_an_id_with_no_possibility_of_duplicating" class="dragging-box-with-no-possibility-of-duplicating-style">
  13. Drag Me
  14. </div>
  15.  
  16. <script type="text/javascript">
  17.  
  18. $(function() {
  19.    
  20.    $("#div_with_an_id_with_no_possibility_of_duplicating").draggable();
  21.  
  22. });
  23.  
  24. </script>
  25.  
  26.  
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 8921
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Nota Febrero 5th, 2013, 12:26 pm

Tengo algunas ideas más para ti.

Intente quitar position: relative de la pare no contenedores o el arrastre me div si existe. Ver si se cambia el funcionamiento de efecto de los valores de posición.

También tengo curiosidad si usas cualquier selectores universales para acolchado o márgenes tales como:

CSS Código: [ Select ]
* { padding:0 }


Volver a cuantas veces se se llama la función, parece correcto que activaría cada vez que el ratón se mueve. Me gustaría descartar que se se llama varias veces cada vez que el ratón se mueve.

¿Has probado todo este escenario en una página básica con CSS básico (no sus sitios completos CSS y JS). También me gustaría confirmar que al menos puedes conseguirlo trabajando correctamente con eso.
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Registrado: Jul 06, 2010
  • Mensajes: 260
  • Status: Offline

Nota Febrero 5th, 2013, 1:08 pm

He hecho una página básica y funciona bien con ninguna demora o por lo menos no uno que es sensible. No noté ningún problema de rendimiento mediante la eliminación de la position: relative y también no utilizar selectores universales. Veo que las diferencias de rendimiento más que poner en las funciones.

Ejemplo
JAVASCRIPT Código: [ Select ]
// This preform the best with very little delay
$(function() {
    $(".draggable").draggable();
});
 
// This adds more delay
$(function() {
           
    // Setup the mousedown function on the draggable class name
    $(".draggable").draggable({
        revert:true,
        helper: function( event ) {
            return $('<img src="images/fam/photo_add.png">');
        }
    });
           
    $(".droppable").droppable({
        greedy: true,
        drop: function( event, ui ) {
            alert('dropped');
        }
    });      
 
    $(".droppable2").droppable({
        greedy: true,
        drop: function( event, ui ) {
            alert('dropped2');
        }
    });
           
});
 
  1. // This preform the best with very little delay
  2. $(function() {
  3.     $(".draggable").draggable();
  4. });
  5.  
  6. // This adds more delay
  7. $(function() {
  8.            
  9.     // Setup the mousedown function on the draggable class name
  10.     $(".draggable").draggable({
  11.         revert:true,
  12.         helper: function( event ) {
  13.             return $('<img src="images/fam/photo_add.png">');
  14.         }
  15.     });
  16.            
  17.     $(".droppable").droppable({
  18.         greedy: true,
  19.         drop: function( event, ui ) {
  20.             alert('dropped');
  21.         }
  22.     });      
  23.  
  24.     $(".droppable2").droppable({
  25.         greedy: true,
  26.         drop: function( event, ui ) {
  27.             alert('dropped2');
  28.         }
  29.     });
  30.            
  31. });
  32.  


La más que poner en las funciones de arrastrables o lanzable retrasar más consoló a las funciones de jQuery UI para esto y visto cada llamada que sucedió, y hay varias funciones que se extienden entre sí que llamada por ejemplo la función drag() se llama unas 8 veces y si añades el arrastre en la la llamada se llama otra vez. Una razón de eso me puse a buscar un ligero arrastre función.

JAVASCRIPT Código: [ Select ]
$(function() {
    $(".draggable").draggable({
        drag: function() { alert('dragging'); }
    });
});
 
  1. $(function() {
  2.     $(".draggable").draggable({
  3.         drag: function() { alert('dragging'); }
  4.     });
  5. });
  6.  

Publicar Información

  • Total de mensajes en este tema: 8 mensajes
  • Usuarios navegando por este Foro: demonmaestro y 134 invitados
  • No puede abrir nuevos temas en este Foro
  • No puede responder a temas en este Foro
  • No puede editar sus mensajes en este Foro
  • No puede borrar sus mensajes en este Foro
  • No puede enviar adjuntos en este Foro
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC