Foros del Web » Programando para Internet » Javascript »

Crear div con mouse click

Estas en el tema de Crear div con mouse click en el foro de Javascript en Foros del Web. Como están amigos del foro, estoy haciendo un pequeño proyecto donde quiero crear Divs de manera visual con la ayuda del mouse, espero que me ...
  #1 (permalink)  
Antiguo 24/01/2012, 17:04
 
Fecha de Ingreso: febrero-2010
Mensajes: 60
Antigüedad: 14 años, 2 meses
Puntos: 0
Crear div con mouse click

Como están amigos del foro, estoy haciendo un pequeño proyecto donde quiero crear Divs de manera visual con la ayuda del mouse, espero que me puedan ayudar. Lo que he pensado es:

-Detectar el clic y guardar las coordenadas de inicio del Div.
-Detectar donde se suelta o nuevamente clic y guarda las coordenadas de cierre de Div.
-Calcular el tamaño del div.
-Crear el div con coordenadas de inicio y tamaño. Mediante css position: absolute.

Esto quería hacerlo con Jquery. Pero me preguntaba si abría alguna función que me facilitase el proceso. Gracias
  #2 (permalink)  
Antiguo 24/01/2012, 17:31
Avatar de madhatterdef  
Fecha de Ingreso: diciembre-2011
Ubicación: argentina
Mensajes: 213
Antigüedad: 12 años, 4 meses
Puntos: 59
Respuesta: Crear div con mouse click

lo que buscas es un efecto
drag and drop

un ej jquery:
Código:
/**
* EasyDrag 1.4 - Drag & Drop jQuery Plug-in
*
* Thanks for the community that is helping the improvement
* of this little piece of code.
*
* For usage instructions please visit http://fromvega.com
*/

(function($){

    // to track if the mouse button is pressed
    var isMouseDown    = false;

    // to track the current element being dragged
    var currentElement = null;

    // callback holders
    var dropCallbacks = {};
    var dragCallbacks = {};

    // global position records
    var lastMouseX;
    var lastMouseY;
    var lastElemTop;
    var lastElemLeft;
    
    // track element dragStatus
    var dragStatus = {};    

    // returns the mouse (cursor) current position
    $.getMousePosition = function(e){
        var posx = 0;
        var posy = 0;

        if (!e) var e = window.event;

        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY) {
            posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
        }

        return { 'x': posx, 'y': posy };
    };

    // updates the position of the current element being dragged
    $.updatePosition = function(e) {
        var pos = $.getMousePosition(e);

        var spanX = (pos.x - lastMouseX);
        var spanY = (pos.y - lastMouseY);

        $(currentElement).css("top",  (lastElemTop + spanY));
        $(currentElement).css("left", (lastElemLeft + spanX));
    };

    // when the mouse is moved while the mouse button is pressed
    $(document).mousemove(function(e){
        if(isMouseDown && dragStatus[currentElement.id] == 'on'){
            // update the position and call the registered function
            $.updatePosition(e);
            if(dragCallbacks[currentElement.id] != undefined){
                dragCallbacks[currentElement.id](e, currentElement);
            }

            return false;
        }
    });

    // when the mouse button is released
    $(document).mouseup(function(e){
        if(isMouseDown && dragStatus[currentElement.id] == 'on'){
            isMouseDown = false;
            if(dropCallbacks[currentElement.id] != undefined){
                dropCallbacks[currentElement.id](e, currentElement);
            }

            return false;
        }
    });

    // register the function to be called while an element is being dragged
    $.fn.ondrag = function(callback){
        return this.each(function(){
            dragCallbacks[this.id] = callback;
        });
    };

    // register the function to be called when an element is dropped
    $.fn.ondrop = function(callback){
        return this.each(function(){
            dropCallbacks[this.id] = callback;
        });
    };
    
    // stop the element dragging feature
    $.fn.dragOff = function(){
        return this.each(function(){
            dragStatus[this.id] = 'off';
        });
    };
    
    
    $.fn.dragOn = function(){
        return this.each(function(){
            dragStatus[this.id] = 'on';
        });
    };

    // set an element as draggable - allowBubbling enables/disables event bubbling
    $.fn.easydrag = function(allowBubbling){

        return this.each(function(){

            // if no id is defined assign a unique one
            if(undefined == this.id || !this.id.length) this.id = "easydrag"+(new Date().getTime());

            // set dragStatus 
            dragStatus[this.id] = "on";
            
            // change the mouse pointer
            $(this).css("cursor", "move");

            // when an element receives a mouse press
            $(this).mousedown(function(e){

                // set it as absolute positioned
                $(this).css("position", "absolute");

                // set z-index
                $(this).css("z-index", "10000");

                // update track variables
                isMouseDown    = true;
                currentElement = this;

                // retrieve positioning properties
                var pos    = $.getMousePosition(e);
                lastMouseX = pos.x;
                lastMouseY = pos.y;

                lastElemTop  = this.offsetTop;
                lastElemLeft = this.offsetLeft;

                $.updatePosition(e);

                return allowBubbling ? true : false;
            });
        });
    };

})(jQuery);
ponelo en
Cita:
jquery.easydrag.js
y en el html

Código:
<html>
    <head>
    <title>EasyDrag Demo</title>
    <script src="jquery.js" type="text/javascript"></script>
    <script src="jquery.easydrag.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function(){
        $("#box1").easydrag();
    });
    </script>
    <style type="text/css">
    #box1 {
        font-family: "Trebuchet MS", Tahoma, Verdana;
        background-color: yellow;
        padding: 5px;
        border: 2px solid orange;
        width: 200px;
    }
    </style>
    </head>
    <body>
    <h3>EasyDrag jQuery Plugin </h3>
    <div id="box1">Versi&oacute;n demo de Easy Drag</div>
    </body>
    </html>
__________________
PD gracias por el karma
  #3 (permalink)  
Antiguo 24/01/2012, 18:35
 
Fecha de Ingreso: febrero-2010
Mensajes: 60
Antigüedad: 14 años, 2 meses
Puntos: 0
Respuesta: Crear div con mouse click

Esto me serviría para mover el div, pero lo que quiero es crearlo desde cero, como si hiciera un recuadro con el mouse y se convierta en un div.
  #4 (permalink)  
Antiguo 24/01/2012, 20:39
 
Fecha de Ingreso: octubre-2010
Mensajes: 107
Antigüedad: 13 años, 6 meses
Puntos: 14
Respuesta: Crear div con mouse click

Prueba con este codigo, lo hize en poco tiempo pero talvez te sirva de base para hacer algo mas elaborado.

Código Javascript:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>Documento sin título</title>
  6. </head>
  7. <script>
  8. i=0;
  9. flag=0;
  10.  
  11. window.onload=function(event){
  12.     window.onclick=rectangulo; 
  13.     }
  14. function rectangulo(event){
  15. if(flag==0){
  16. var x=event.clientX;
  17. var y=event.clientY;
  18. var div=document.createElement("div");
  19. div.id=i
  20. i++;
  21. div.style.position="absolute";
  22. div.style.zIndex=i;
  23. div.style.left=x+"px";
  24. div.style.top=y+"px";
  25. div.style.backgroundColor="#000";
  26. document.body.appendChild(div);
  27. window.onmousemove=function(event){
  28. div.style.width=(event.clientX-x)+"px";
  29. div.style.height=(event.clientY-y)+"px";
  30. }
  31. flag=1;
  32. }
  33. else{flag=0; window.onmousemove=false;
  34.     }
  35.     }
  36.  
  37.  
  38. </script>
  39. <body>
  40. </body>
  41. </html>


Si no entiendes algo o necesitas mas ayuda no dudes en preguntar.
  #5 (permalink)  
Antiguo 25/01/2012, 08:45
Avatar de madhatterdef  
Fecha de Ingreso: diciembre-2011
Ubicación: argentina
Mensajes: 213
Antigüedad: 12 años, 4 meses
Puntos: 59
Respuesta: Crear div con mouse click

perdón por mi error
__________________
PD gracias por el karma
  #6 (permalink)  
Antiguo 25/01/2012, 12:45
 
Fecha de Ingreso: febrero-2010
Mensajes: 60
Antigüedad: 14 años, 2 meses
Puntos: 0
Respuesta: Crear div con mouse click

MARCASTELEON gracias por el código ahora lo estoy adaptando a mis necesidades. Mas bien una pregunta las coordenadas que calcula son respecto al documento, como podría hacer para que sean respecto a un contenedor div. Porque luego quiero almacenarlas para enviarlas a una base de datos. Este es mi código:
Código Javascript:
Ver original
  1. <script>
  2. $(document).ready(function(){
  3. i=0;
  4. flag=0;
  5. allcontxt = document.getElementById('AllCont_Texto');
  6. allcontxt.onclick=rectangulo;*
  7. function rectangulo(event){
  8. if(flag==0){
  9. var x=event.clientX;
  10. var y=event.clientY;
  11. var div=document.createElement("div");
  12. div.id='Cont_Texto'+i;
  13. i++;
  14. div.style.position="absolute";
  15. div.style.zIndex=82;
  16. div.style.left=x+"px";
  17. div.style.top=y+"px";
  18. div.style.backgroundColor="#000";
  19. allcontxt.appendChild(div);
  20. allcontxt.onmousemove=function(event){
  21. div.style.width=(event.clientX-x)+"px";
  22. div.style.height=(event.clientY-y)+"px";
  23. }
  24. flag=1;
  25. }
  26. else{flag=0; allcontxt.onmousemove=false;
  27.  }
  28.  }
  29. });
  30.  
  31. </script>

El único inconveniente es como te decia: las coordenadas son respecto al documento y cuando se traza lo hace dentro de un div, con lo que varia el lugar de trazado.

Última edición por clarkpler; 25/01/2012 a las 19:13
  #7 (permalink)  
Antiguo 25/01/2012, 21:18
 
Fecha de Ingreso: febrero-2010
Mensajes: 60
Antigüedad: 14 años, 2 meses
Puntos: 0
Respuesta: Crear div con mouse click

Ya Solucioné el problema; acá dejo el código por si lo necesita alguien; aclaro que está mezclado con Jquery pues aún no conozco muy bien el javascript.
Código Javascript:
Ver original
  1. <script>
  2. $(document).ready(function(){
  3. i=0; //Valor dinumeracion div inicial
  4. flag=0;
  5. allcontxt = document.getElementById('AllCont_Texto');
  6. allcontxt.onclick=rectangulo;*
  7.  
  8. posicionReal = $("#AllCont_Texto").offset();
  9. var yc=posicionReal.top;
  10. var xc=posicionReal.left;
  11.  
  12. ////Funcion que crea divs
  13. //Si no se a dado clic el marcador sera 0; si se da clic será 1
  14. // Si marcado es 0, condicion inicial -> obtenemos las coordenadas del primer click x,y; y creamos el div con posicion absoluta x y y
  15. // Luego activamos la la deteccion de movimiento del mouse y vamos calculando continuamente la posicion para asignar el tamaño al div
  16. // cambiamos el marcador a 1; con lo que al siguiente clic se desactivara la deteccion del movimiento y obtendremos el div final.
  17. function rectangulo(event){
  18. if(flag==0){
  19. var x=event.pageX-xc;
  20. var y=event.pageY-yc;
  21. var div=document.createElement("div");
  22. div.id='Cont_Texto'+i;
  23. i++;
  24. div.style.position="absolute";
  25. div.style.zIndex=82;
  26. div.style.left=x+"px";
  27. div.style.top=y+"px";
  28. div.style.backgroundColor="#000";
  29. allcontxt.appendChild(div);
  30. allcontxt.onmousemove=function(event){
  31. div.style.width=(event.pageX-xc-x)+"px";
  32. div.style.height=(event.pageY-yc-y)+"px";
  33. }
  34. flag=1;
  35. }
  36. else{flag=0; allcontxt.onmousemove=false;
  37. * * }
  38. * * }
  39. *});
  40. *
  41. </script>
  #8 (permalink)  
Antiguo 26/01/2012, 06:13
 
Fecha de Ingreso: octubre-2010
Mensajes: 107
Antigüedad: 13 años, 6 meses
Puntos: 14
Respuesta: Crear div con mouse click

siento la tardanza en responder, que bueno que lo has resuelto .
  #9 (permalink)  
Antiguo 20/02/2012, 11:39
Avatar de capa  
Fecha de Ingreso: octubre-2006
Mensajes: 86
Antigüedad: 17 años, 6 meses
Puntos: 1
Respuesta: Crear div con mouse click

Hola MARCASTELEON

excelente la iniciativa y me recode a una de mis inquietudes hace mucho tiempo, como calculas si arrastras el Mouse hacia la izquierda o arriba, tomando el punto de referencia del click del Mouse, bueno lo hice moviendo las coordenadas, abra otro metodo o quizás tengas algunas otra solución?

Saludos.
__________________
Destreza..<?phs La felicidad es un trayecto ?>

Etiquetas: mouse
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 00:22.