Visualizzazione dei risultati da 1 a 8 su 8

Discussione: elemento trascinabile

  1. #1
    Utente di HTML.it L'avatar di deleted_id_48586
    Registrato dal
    Nov 2002
    Messaggi
    1,732

    elemento trascinabile

    Ciao a tutti,

    sto studiando da poco JS quindi ci capisco veramente poco sugli eventi.

    Il mio problema è che vorrei realizzare (come esercizio) un DIV trascinabile all'interno della finestra del browser.

    Ho creato un paio di funzioni ma non sò come passare i valori della prima init() alla seconda sposta().

    codice:
    function init(evt) {		
        var e = (evt) ? evt : window.event;
        var posX = (e.pageX) ? e.pageX : (e.clientX + document.body.scrollTop);
        var posY = (e.pageY) ? e.pageY : (e.clientY + document.body.scrollLeft);					}							
            						
    function sposta(elem) {								
        elem.style.top = posY + 'px';
        elem.style.left = posX + 'px';								
    }

    Nel body ho messo :
    <body onmousemove="init(event)">

    mentre nel DIV:
    onmousedown="sposta(this)"

    Sò che il problema principale è l'ambito di validità delle variabili posX e posY ma se metto davanti GLOBAL non funziona comunque.

    Ho un pò di confusione, mi potreste aiutare?

    Grazie.

    P.S.
    Inoltre su IE7 le proprietà document.body.scrollLeft e scrollTop mi restituiscono sempre 0 ... com'è possibile?!

  2. #2
    Utente di HTML.it L'avatar di deleted_id_48586
    Registrato dal
    Nov 2002
    Messaggi
    1,732
    Uhm vediamo, sono arrivato qua:


    codice:
    function init(evt) {
    			
           var e = (evt) ? evt : window.event;
           var elem = (e.target) ? e.target : e.srcElement;
                         				
           var posX = (e.pageX) ? e.pageX : (e.clientX + document.body.scrollTop);
           var posY = (e.pageY) ? e.pageY : (e.clientY + document.body.scrollLeft);	
    				
    	var x = posX + 'px';
    	var y = posY + 'px';
    				
    								
             function sposta(evt) {					                
              elem.style.left = x;
              elem.style.top = y;   					         
             }							
                
             elem.onmousemove = sposta;
    				
    								
    }
    appena entro sul DIV lo stesso si incolla nelle sue coordinate 0,0 (angolo in altro a sinistra) al puntatore del mouse e lo segue:

    Come faccio ad attivarlo solo al mousedown e disattivarlo al mouseup?

    Grazie.

  3. #3
    Codice PHP:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <
    html xmlns="http://www.w3.org/1999/xhtml">
    <
    head>
    <
    title>Untitled Document</title>
    <
    meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <
    style type="text/css">
    <!--
    * {
        
    margin0px;
        
    padding0px;
    }
    {
        
    text-decorationnone;
    }
    .
    drag {border1px solid blackbackground-colorrgb(240240240); positionrelativepadding0.5emmargin0 0 0.5em 1.5emcursormove;}
    -->
    </
    style>
    </
    head>

    <
    body>
    <
    div class="drag">Item 1</div>
    <
    div class="drag">Item 2</div>
    <
    pre id="debug"> </pre>
    <
    script language="JavaScript" type="text/JavaScript">
    <!--
    var 
    _startX 0;            // mouse starting positions
    var _startY 0;
    var 
    _offsetX 0;            // current element offset
    var _offsetY 0;
    var 
    _dragElement;            // needs to be passed from OnMouseDown to OnMouseMove
    var _oldZIndex 0;            // we temporarily increase the z-index during drag
    var _debug = $('debug');    // makes life easier
    function InitDragDrop(){
        
    document.onmousedown OnMouseDown;
        
    document.onmouseup OnMouseUp;
    }
    function 
    OnMouseDown(e){
        if (!
    e) {window.event; }
        var 
    target e.target != null e.target e.srcElement;
        
    _debug.innerHTML target.className == 'drag' 'draggable element clicked' 'NON-draggable element clicked';
        
    // for IE, left click == 1
        // for Firefox, left click == 0
        
    if (((e.button == && window.event != null) || (e.button == 0)) && target.className == 'drag'){
            
    // grab the mouse position
            
    _startX e.clientX;
            
    _startY e.clientY;
            
    // grab the clicked element's position
            
    _offsetX ExtractNumber(target.style.left);
            
    _offsetY ExtractNumber(target.style.top);
            
    // bring the clicked element to the front while it is being dragged
            
    _oldZIndex target.style.zIndex;
            
    target.style.zIndex 10000;
            
    // we need to access the element in OnMouseMove
            
    _dragElement target;
            
    // tell our code to start moving the element with the mouse
            
    document.onmousemove OnMouseMove;
            
    // cancel out any text selections
            
    document.body.focus();
            
    // prevent text selection in IE
            
    document.onselectstart = function () { return false; };
            
    // prevent text selection (except IE)
            
    return false;
        }
    }
    function 
    OnMouseMove(e){
        if (!
    e) {window.event; }
        
    // this is the actual "drag code"
        
    _dragElement.style.left = (_offsetX e.clientX _startX) + 'px';
        
    _dragElement.style.top = (_offsetY e.clientY _startY) + 'px';
        
    _debug.innerHTML '(' _dragElement.style.left ', ' _dragElement.style.top ')';    
    }
    function 
    OnMouseUp(e){
        if (
    _dragElement != null){
            
    _dragElement.style.zIndex _oldZIndex;
            
    // we're done with these events until the next OnMouseDown
            
    document.onmousemove null;
            
    document.onselectstart null;
            
    // this is how we know we're not dragging        
            
    _dragElement null;
            
    _debug.innerHTML 'mouse up';
        }
    }
    function $(
    id){
        return 
    document.getElementById(id);
    }
    function 
    ExtractNumber(value){
        var 
    parseInt(value);
        return 
    == null || isNaN(n) ? n;
    }
    InitDragDrop();
            
    //-->
    </script>
    </body>
    </html> 

    devarticles


    Without faith, nothing is possible. With it, nothing is impossible
    http://ilwebdifabio.it

  4. #4
    Utente di HTML.it L'avatar di deleted_id_48586
    Registrato dal
    Nov 2002
    Messaggi
    1,732
    Grazie mille Whisher, se non ci fossi bisognerebbe inventarti!

    Adesso mi studio il codice.

    Certo che JS è proprio ostioso.

  5. #5
    Utente di HTML.it L'avatar di deleted_id_48586
    Registrato dal
    Nov 2002
    Messaggi
    1,732
    Scusami ancora ma non ho capito questa funzione:

    codice:
    function $(id){
        return document.getElementById(id);
    }
    in particolare cosa significa quel $ al posto del nome della funzione?

    Grazie.

  6. #6
    Originariamente inviato da Sgurbat
    Scusami ancora ma non ho capito questa funzione:

    codice:
    function $(id){
        return document.getElementById(id);
    }
    in particolare cosa significa quel $ al posto del nome della funzione?

    Grazie.
    La funziona (è una semplice shortcut) ti ritorna l'elemento
    invece di fare
    var pippo= document.getElementById('pippo');
    poi fare

    var pippo= $('pippo');


    è anche la versione semplificata
    di questa presa a prestito dalla
    libreria prototype

    Codice PHP:
    function $(){
        var 
    elements = new Array();
        for (var 
    0;i<arguments.length;i++){
            var 
    element arguments[i];
            if (
    typeof element == 'string'){
              
    element document.getElementById(element);
            }
            if (
    arguments.length == 1){
              return 
    element;
            }
            
    elements.push(element);
          }
        return 
    elements;
    };

    //con questa poi fare una cosa del genere

    var pippo= $('pippo1','pippo2','pippo3'); 
    a cui puoi passare + argomenti
    ed ottenere un array di obj.




    Il carattere $ è un carattere come un altro.


    Without faith, nothing is possible. With it, nothing is impossible
    http://ilwebdifabio.it

  7. #7
    Utente di HTML.it L'avatar di oskaron
    Registrato dal
    Sep 2006
    Messaggi
    344
    vediti alcune librerie come script.aculo.us anche

  8. #8
    A propo di librerie
    prova questa una piccola classe molto
    cool


    Without faith, nothing is possible. With it, nothing is impossible
    http://ilwebdifabio.it

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.