Latest web development tutorials

jQuery UI exemplo - drag (Draggable)

Permitindo que o mouse para mover o elemento.

Para mais detalhes sobre a interação draggable, consulte a documentação da API pode arrastar e soltar widgets (o arrastáveis o Widget) .

A função padrão

Ativar o recurso draggable em qualquer elemento DOM. Clicando e arrastando o mouse na janela de exibição para mover o objeto arrastado.

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> arrastar jQuery UI (Draggable) - A função padrão </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  #draggable {width: 150px; height: 150px; padding: 0.5em;}
  </ Style>
  <Script>
  $ (Function () {
    $ ( "#draggable") .draggable ();
  });
  </ Script>
</ Head>
<Body>
 
<Div id = "arrastado" class = "ui-widget-content">
  <P> Por favor me arrastar! </ P>
</ Div>
 
 
</ Body>
</ Html>

rolagem automática

o deslocamento automático no documento quando o draggable transferidas para fora da janela. Defina o scroll opção como true para ativar a rolagem automática, fine-tuning, a velocidade de rolagem ao percorrer o gatilho scrollSensitivity e scrollSpeed definição de opções.

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> jQuery UI arrasto (Draggable) - rolagem automática </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  #draggable, # draggable2, # draggable3 {width: 100px; height: 100px; padding: 0.5em; float: left; margin: 0 10px 10px 0;}
  </ Style>
  <Script>
  $ (Function () {
    $ ( "#draggable") .draggable ({Role: true});
    $ ( "# Draggable2") .draggable ({rolagem: true, scrollSensitivity: 100});
    $ ( "# Draggable3") .draggable ({rolagem: true, Scrollspeed: 100});
  });
  </ Script>
</ Head>
<Body>
 
<Div id = "arrastado" class = "ui-widget-content">
  <P> Scroll é definido como verdadeiro, a configuração padrão </ p>
</ Div>
 
<Div id = "draggable2" class = "ui-widget-content">
  <P> scrollSensitivity a 100 </ p>
</ Div>
 
<Div id = "draggable3" class = "ui-widget-content">
  <P> Scrollspeed a 100 </ p>
</ Div>
 
<Div style = "height: 5000px; width: 1px;"> </ div>
 
 
</ Body>
</ Html>

movimento restrita

área Draggable definida pelo limite para restringir o movimento de cada arrastado. Definir axis opções para limitar caminho draggable para o eixo x ou eixo-y, ou containment opção para especificar um pai elemento DOM ou um seletor jQuery, como "documento. '.

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> jQuery UI arrasto (Draggable) - movimento restrito </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  .draggable {width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0;}
  #draggable, # draggable2 {margin-bottom: 20px;}
  #draggable {cursor: n-redimensionamento;}
  # Draggable2 {cursor: e-redimensionamento;}
  # Containment-wrapper {width: 95%; height: 150px; border: 2px #ccc sólida; padding: 10px;}
  h3 {clear: left;}
  </ Style>
  <Script>
  $ (Function () {
    $ ( "#draggable") .draggable ({Axis: "y"});
    $ ( "# Draggable2") .draggable ({eixo: "x"});
 
    $ ( "# Draggable3") .draggable ({contenção: "# contenção-wrapper", desça: false});
    $ ( "# Draggable5") .draggable ({contenção: "pai"});
  });
  </ Script>
</ Head>
<Body>
 
<H3> movimento ao longo do eixo de restrição: </ h3>
 
<Div id = "arrastado" class = "draggable ui-widget-content">
  <P> Apenas arraste verticais </ p>
</ Div>
 
<Div id = "draggable2" class = "draggable ui-widget-content">
  <P> Apenas arraste horizontal </ p>
</ Div>
 
<H3> ou movimento restrito em outro elemento DOM: </ h3>
<Div id = "contenção-wrapper">
  <Div id = "draggable3" class = "draggable ui-widget-content">
    <P> Eu estava constrangida em uma caixa </ p>
  </ Div>
 
  <Div class = "draggable ui-widget-content">
    <P id = "draggable5" class = "ui-widget-header"> Eu estava confinado dentro do elemento pai </ p>
  </ Div>
</ Div>
 
 
</ Body>
</ Html>

cursor Estilo

Quando arrasta o objecto para posicionar o cursor. Por padrão, o cursor está no meio arrastado objeto. Use cursorAt opção para especificar a posição em relação ao outro (especificado em relação a um alto valor de pixel, direita e inferior, à esquerda do) do arrastáveis. Ao fornecer um valor cursor CSS válido com as cursor opções para personalizar a aparência do cursor. valores de cursor CSS válidos incluem: padrão, movimento, ponteiro, cruz, e assim por diante.

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> jQuery UI arrasto (Draggable) - Cursor Estilo </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  #draggable, # draggable2, # draggable3 {width: 100px; height: 100px; padding: 0.5em; float: left; margin: 0 10px 10px 0;}
  </ Style>
  <Script>
  $ (Function () {
    $ ( "#draggable") .draggable ({Cursor: "mover", cursorAt: {top: 56, para a esquerda: 56}});
    $ ( "# Draggable2") .draggable ({cursor: "mira", cursorAt: {top: -5, esquerda: -5}});
    $ ( "# Draggable3") .draggable ({cursorAt: {bottom: 0}});
  });
  </ Script>
</ Head>
<Body>
 
<Div id = "arrastado" class = "ui-widget-content">
  <P> Eu estou sempre no meio (em relação ao mouse) </ p>
</ Div>
 
<Div id = "draggable2" class = "ui-widget-content">
  <P> O meu cursor é esquerda -5 e superior -5 </ p>
</ Div>
 
<Div id = "draggable3" class = "ui-widget-content">
  <P> A minha única controlar a posição do cursor valores 'de fundo' </ p>
</ Div>
 
 
</ Body>
</ Html>

início retardado

Por delay milissegundos de atraso comece a arrastar as configurações de opção. Por distance opção é pressionado e arraste o cursor para o pixel especificado antes de permitir arrastar e soltar.

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> jQuery UI arrasto (Draggable) - início retardado </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  #draggable, # draggable2 {width: 120px; height: 120px; padding: 0.5em; float: left; margin: 0 10px 10px 0;}
  </ Style>
  <Script>
  $ (Function () {
    $ ( "#draggable") .draggable ({Distância: 20});
    $ ( "# Draggable2") .draggable ({atraso: 1000});
    $ ( ".ui-Draggable") .disableSelection ();
  });
  </ Script>
</ Head>
<Body>
 
<Div id = "arrastado" class = "ui-widget-content">
  <P> Apenas quando eu arrastar um pixel 20, e começou a arrastar </ p>
</ Div>
 
<Div id = "draggable2" class = "ui-widget-content">
  Após <p> Não importa o quanto a distância que você tem que arrastar e arrastar começou a esperar por 1000ms </ p>
</ Div>
 
 
</ Body>
</ Html>

evento

arrastáveis em start , drag e stop eventos. Arrastando o início gatilho start do evento, desencadeada durante a arrastar drag evento, acionado quando o arrasto parada stop evento.

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> arrastar jQuery UI (Draggable) - eventos </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  #draggable {width: 16EM; padding: 0 1em;}
  #draggable ul li {margin: 1em 0; padding: 0.5em 0;} * html #draggable ul li {height: 1%;}
  #draggable ul li span.ui-icon {float: left;}
  #draggable span.count ul li {font-weight: bold;}
  </ Style>
  <Script>
  $ (Function () {
    var $ start_counter = $ ( "# event-start"),
      $ Drag_counter = $ ( "# evento de arrastar"),
      $ Stop_counter = $ ( "# event-stop"),
      contagens = [0, 0, 0];
 
    $ ( "#draggable") .draggable ({
      começar: function () {
        contagens de [0] ++;
        updateCounterStatus ($ start_counter, as contagens de [0]);
      },
      arrastar: function () {
        contagens de [1] ++;
        updateCounterStatus ($ drag_counter, as contagens de [1]);
      },
      parar: function () {
        contagens de [2] ++;
        updateCounterStatus ($ stop_counter, as contagens de [2]);
      }
    });
 
    funcionar updateCounterStatus ($ event_counter, NEW_COUNT) {
      // Atualizado primeiro estado visual ...
      if (! $ event_counter.hasClass ( "ui-state-hover")) {
        $ Event_counter.addClass ( "ui-state-hover")
          . .siblings () removeClass ( "ui-state-hover");
      }
      // ... Então atualizar os números $ ( "span.count", $ event_counter) .text (NEW_COUNT);
    }
  });
  </ Script>
</ Head>
<Body>
 
<Div id = "arrastado" class = "ui ui-widget-widget-content">
 
  <P> Por favor me arrastar, desencadeando uma cadeia de eventos. </ P>
 
  <Class = Ul "ui-helper-reset">
    <Li id = "evento-start" class = "-ui-estado padrão ui-canto-all"> <span class = "ui-icon ui-icon-play"> </ span> "start" é chamado <span class = "contagem"> 0 </ span> x </ li>
    <Li id = "evento de arrastar" class = "-ui-estado padrão ui-canto-all"> <span class = "ui-icon ui-ícone-seta-4"> </ span> "arrastar" é chamado <span class = "contagem"> 0 </ span> x </ li>
    <Li id = "evento-stop" class = "-ui-estado padrão ui-canto-all"> <span class = "ui-icon ui-icon-stop"> </ span> "stop" é chamado <span class = "contagem"> 0 </ span> x </ li>
  </ Ul>
</ Div>
 
 
</ Body>
</ Html>

alças

Só é permitida quando a parte cursor especificado arrasto sobre draggable. Use handle opção para especificar o elemento (ou grupo de elementos) do seletor jQuery para o objeto arrastado.

Ou prevenir arrastando quando o cursor está sobre um elemento específico (ou grupo de elementos) dentro do draggable. Use a opção de cancelar para especificar um seletor jQuery sobre os quais a "cancelar" a funcionalidade de arrastável.

Ou quando o elemento especificado cursor (ou grupo de elementos) dentro do arrasto permitido draggable. Use handle opção para especificar cancelar a função de arrastar seletor jQuery.

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> arrastar jQuery UI (Draggable) - Cabos </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  #draggable, # draggable2 {width: 100px; height: 100px; padding: 0.5em; float: left; margin: 0 10px 10px 0;}
  p #draggable {cursor: move;}
  </ Style>
  <Script>
  $ (Function () {
    $ ( "#draggable") .draggable ({Handle: "p"});
    $ ( "# Draggable2") .draggable ({cancelar: "p.ui-widget-header"});
    $ ( "Div, p") .disableSelection ();
  });
  </ Script>
</ Head>
<Body>
 
<Div id = "arrastado" class = "ui-widget-content">
  <P class = "ui-widget-header"> Você só pode arrastar e soltar dentro desta faixa I </ p>
</ Div>
 
<Div id = "draggable2" class = "ui-widget-content">
  <P> Você pode me levar em torno de arrastar & hellip; </ p>
  <P class = "ui-widget-header"> & hellip; mas você não pode arrastar-me </ p> Nesta faixa
</ Div>
 
 
</ Body>
</ Html>

local de restauração

Tal como acontece com valores booleanos revert quando a opção arrastável para parar de arrastar, o retorno draggable (ou seu assistente) para o local original.

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> jQuery UI arrasto (Draggable) - Restaurar Localização </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  #draggable, # draggable2 {width: 100px; height: 100px; padding: 0.5em; float: left; margin: 0 10px 10px 0;}
  </ Style>
  <Script>
  $ (Function () {
    $ ( "#draggable") .draggable ({Reverter: true});
    $ ( "# Draggable2") .draggable ({reverter: true, ajudante: "clone"});
  });
  </ Script>
</ Head>
<Body>
 
<Div id = "arrastado" class = "ui-widget-content">
  <P> Restaurar </ p>
</ Div>
 
<Div id = "draggable2" class = "ui-widget-content">
  <P> Restaurar Assistente </ p>
</ Div>
 
 
</ Body>
</ Html>

Encaixe de elementos de rede ou

Alinhar elementos fronteiras DOM internos ou externos que podem ser arrastadas. O uso de snap , snapMode (Interior, Exterior, ambos) e snapTolerance (quando chamando alinhado com a distância draggable entre elementos em pixels) opção.

Alinhar à grade ou arrastado. Por grid opção de tamanho para definir as células da grade (pixels de altura ou largura).

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> jQuery UI arrasto (Draggable) - Alinhar a elementos grade ou </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  .draggable {width: 90px; height: 80px; padding: 5px; float: left; margin: 0 10px 10px 0; font-size: .9em;}
  .ui-widget-header p, .ui-widget-content p {margin: 0;}
  #snaptarget {height: 140px;}
  </ Style>
  <Script>
  $ (Function () {
    $ ( "#draggable") .draggable ({Snap: true});
    $ ( "# Draggable2") .draggable ({estalo: ".ui-widget-header"});
    $ ( "# Draggable3") .draggable ({estalo: ".ui-widget-header", SNAPMODE: "exterior"});
    $ ( "# Draggable4") .draggable ({grelha: [20, 20]});
    $ ( "# Draggable5") .draggable ({grelha: [80, 80]});
  });
  </ Script>
</ Head>
<Body>
 
<Div id = "snaptarget" class = "ui-widget-header">
  <P> Eu sou uma meta alinhados </ p>
</ Div>
 
style="clear:both"> <br
 
<Div id = "arrastado" class = "draggable ui-widget-content">
  <P> Padrão (SNAP: true), alinhado a todas as outras elemento arrastável </ p>
</ Div>
 
<Div id = "draggable2" class = "draggable ui-widget-content">
  <P> Eu só alinhado à grande caixa </ p>
</ Div>
 
<Div id = "draggable3" class = "draggable ui-widget-content">
  <P> Eu só alinhado com o bordo exterior da caixa grande </ p>
</ Div>
 
<Div id = "draggable4" class = "draggable ui-widget-content">
  <P> I alinhados a uma grade de 20 x 20 </ p>
</ Div>
 
<Div id = "draggable5" class = "draggable ui-widget-content">
  <P> I alinhados a uma grade de 80 x 80 </ p>
</ Div>
 
 
</ Body>
</ Html>

feedback visual

Fornecer feedback para o usuário, como assistente para a forma como os objetos arrastados. helper opção aceita valores "original" (com os objetos que podem ser arrastadas do cursor), "clone" (com a cópia draggable cursor), ou uma função retorna o elemento DOM (o elemento durante uma arrastar o cursor pela tela). Por opacity opção controla assistente de transparência.

Para distinguir o que é uma draggable é arrastado, vamos draggable em movimento para manter a frente. Se você está arrastando, usando zIndex opção para definir a altura do assistente z-index, ou usar a stack opção para garantir que quando você parar de arrastar, o último sendo arrastado item de sempre aparece no topo do grupo com outros projetos.

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> jQuery UI arrasto (Draggable) - feedback visual </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  #draggable, # draggable2, # draggable3, #set div {width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0;}
  #draggable, # draggable2, # draggable3 {margin-bottom: 20px;}
  #set {clear: both; float: left; width: 368px; height: 120px;}
  p {clear: both; margin: 0; padding: 1em 0;}
  </ Style>
  <Script>
  $ (Function () {
    $ ( "#draggable") .draggable ({Helper: "original"});
    $ ( "# Draggable2") .draggable ({opacidade: 0.7, ajudante: "clone"});
    $ ( "# Draggable3") .draggable ({
      cursor: "mover",
      cursorAt: {top: -12, esquerda: -20},
      helper: function (event) {
        return $ ( "<div class = 'ui-widget-header'> Eu sou um auxiliar personalizado </ div>");
      }
    });
    $ ( "#set Div") .draggable ({empilhar: "div #set"});
  });
  </ Script>
</ Head>
<Body>
 
<H3 class = "docs"> helper: </ h3>
 
<Div id = "arrastado" class = "ui-widget-content">
  <P> ORIGINAL </ p>
</ Div>
 
<Div id = "draggable2" class = "ui-widget-content">
  <P> translúcida clone </ p>
</ Div>
 
<Div id = "draggable3" class = "ui-widget-content">
  <P> assistente Personalizado (em conjunto com cursorAt) </ p>
</ Div>
 
<H3 class = "docs"> pilha: </ h3>
<Div id = "set">
  <Div class = "ui-widget-content">
    <P> Nós somos draggables .. </ p>
  </ Div>
 
  <Div class = "ui-widget-content">
    <P> .. é z-index é controlado automaticamente .. </ p>
  </ Div>
 
  <Div class = "ui-widget-content">
    <P> .. com opções de pilha. </ P>
  </ Div>
</ Div>
 
 
</ Body>
</ Html>

jQuery UI arrastável + Ordenável

Draggable e Ordenável de interação perfeita.

<! DOCTYPE html>
<Html lang = "PT">
<Head>
  <Charset Meta = "utf-8">
  <Title> jQuery UI arrasto (Draggable) + Sort (Ordenável) </ title>
  <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <Script src = "// code.jquery.com/jquery-1.9.1.js"> </ script>
  <Script src = "// code.jquery.com/ui/1.10.4/jquery-ui.js"> </ script>
  <Link rel = "stylesheet" href = "http://jqueryui.com/resources/demos/style.css">
  <Style>
  ul {list-style-type: none; margin: 0; padding: 0; margin-bottom: 10px;}
  li {margin: 5px; padding: 5px; width: 150px;}
  </ Style>
  <Script>
  $ (Function () {
    $ ( "#sortable") .sortable ({
      revertem: true
    });
    $ ( "#draggable") .draggable ({
      connectToSortable: "#sortable",
      helper: "clone",
      revertem: "inválido"
    });
    $ ( "Ul, li") .disableSelection ();
  });
  </ Script>
</ Head>
<Body>
 
<Ul>
  <Li id = "arrastado" class = "ui-state-highlight"> Por favor me arrastar </ li>
</ Ul>
 
<Ul id = "classificáveis">
  <LI class = "ui-estado-padrão"> Item 1 </ li>
  <LI class = "ui-estado-padrão"> Item 2 </ li>
  <LI class = "ui-estado-padrão"> Item 3 </ li>
  <LI class = "ui-estado-padrão"> Item 4 </ li>
  <LI class = "ui-estado-padrão"> Item 5 </ li>
</ Ul>
 
 
</ Body>
</ Html>