Ir para conteúdo
Fórum Script Brasil
  • 0

mover div com click do mouse


ktinho

Pergunta

como mover uma div com clicke do mouse? eu tenho esse script que uma imagem acompanha o mouse mas eu não sei qual funçao usar para que ao clickar em um lugar da pagina seja movido a imagem veja o script:

<html> 
<head> 
        <title>HTML5 WebSocket Example with PHP5 Server</title> 
        <script type="text/javascript" src="jquery.min.js"></script> 
        <script type="text/javascript"> 

                var socket;

                function dump(data) {
                        var content = '';
                        for (userId in data) {
                                if (data[userId].position) {
                                        var pos = data[userId].position.split(',');
                                        content += '<li class="user"><div class="icon" style="background:' + data[userId].color + ';"></div>' + data[userId].ip + ': ' + pos[0] + 'x' + pos[1] + '</li>';
                                }
                        }
                        $('#console ul').html(content);
                }
                
                function renderPosition(u, x, y, c) {
                        if ($('#'+u).length == 0) {
                                $('<div class="cursor" id="' + u + '"></div>').appendTo('body');
                        }
                        $('#'+u).css('left', x+'px');
                        $('#'+u).css('top', y+'px');
                        $('#'+u).css('background', c);
                }
                
                function send(x, y) {
                        var msg = x + ',' + y;
                        socket.send(msg);
                }
                
                function init() {
                        var host = "ws://localhost:8000/sockethtml5/server.php";
                        try {
                                socket = new WebSocket(host); 
                                socket.onopen = function(msg){ };
                                socket.onmessage = function(msg){
                                        if (msg.data) {
                                                eval('var data = ' + msg.data + ';');
                                                for (userId in data) {
                                                        if (data[userId].position) {
                                                                var pos = data[userId].position.split(',');
                                                                var color = data[userId].color;
                                                                renderPosition(userId, pos[0], pos[1], color); 
                                                        }
                                                }
                                                dump(data);
                                        }
                                };
                                socket.onclose = function(msg){ };
                        } catch(ex){ alert(ex); }

                        $('body').bind('mousemove', function(evt){
                                if (evt.clientX && evt.clientY) {
                                        send(parseInt(evt.clientX), parseInt(evt.clientY));
                                }
                        });
                }
        
        </script> 
        <style type="text/css"> 
                .cursor { position:absolute; left:0; top:0; width:100px; height:100px; background-image: url(321.gif); background-repeat: no-repeat; }
                .icon { float:left; width:10px; height:10px; margin-right:5px; }
                #console, #info { font:12px arial,helvetica,sans-serif; margin:20px; padding:20px; background:#f1f1f1; width:250px; }
                #console { background:url(http://www.easevents.com/pdacamps/kamila/funny-cat.jpg) no-repeat center center; font-size:10px; height:250px; overflow:auto; }
                #console ul { margin:0; padding:0; }
                .user { background:#fff; padding:5px; list-style-type:none; }
                h1 { font-size:20px; margin:0; }
                h2 { margin:0 0 10px 0; }
                button { position:absolute; right:0; bottom:0; font-size:20px; padding:5px 10px; margin:40px; }
        </style> 
</head> 
<body id="body" onLoad="init()"> 
        <div id="info"> 
                <h1>HTML5 Websockets Test</h1> 
                <a href="http://bohuco.net/blog/2010/07/html5-websockets-example/">More Infos at bohuco.net/blog</a> 
        </div> 
        <div id="console"> 
                <h2>Current Users ...</h2> 
                <ul></ul> 
        </div> 
        <button onClick="document.location = 'http://bohuco.net/blog/2010/07/html5-websockets-example/';">More Infos &raquo;</button> 
</body> 
</html>

preciso que a imagem mova ao clickar ao invez de seguir o mouse mas cassei e não achei uma funçao que faça isso alguém me ajuda?

Link para o comentário
Compartilhar em outros sites

2 respostass a esta questão

Posts Recomendados

  • 0

i aew ktinho, bom aproveita que você está utilizando o jquery e pega o jquery-ui, ele já tem alguns caras que facilitam isso, saca só um exemplo:

dropImagem.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Drop de imagem</title>
	<link rel="stylesheet" href="jquery-ui-1.8.9.custom/development-bundle/themes/base/jquery.ui.all.css">
	<script src="jquery-ui-1.8.9.custom/development-bundle/jquery-1.4.4.js"></script>
	<script src="jquery-ui-1.8.9.custom/development-bundle/ui/jquery.ui.core.js"></script>
	<script src="jquery-ui-1.8.9.custom/development-bundle/ui/jquery.ui.widget.js"></script>

	<script src="jquery-ui-1.8.9.custom/development-bundle/ui/jquery.ui.mouse.js"></script>
	<script src="jquery-ui-1.8.9.custom/development-bundle/ui/jquery.ui.draggable.js"></script>
	<script src="jquery-ui-1.8.9.custom/development-bundle/ui/jquery.ui.droppable.js"></script>
	<link rel="stylesheet" href="jquery-ui-1.8.9.custom/development-bundle/demos/demos.css">
	<style>
	#draggable { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }
	#droppable { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; }
	</style>
	<script>
	$(function() {
		$( "#draggable" ).draggable();
		$( "#droppable" ).droppable({
			drop: function( event, ui ) {
				$( this )
					.addClass( "ui-state-highlight" )
					.find( "p" )
						.html( "Funcionou!" );
			}
		});
	});
	</script>
</head>
<body>
<div><h1>arraste essa imagem</h1></div>
<img id="draggable" class="ui-widget-content" src='http://scriptbrasil.com.br/forum/style_images/sb_images/logo4.jpg' />
<div id="droppable" class="ui-widget-header">
	<p>Joga a imagem aqui</p>
</div>
</body>
</html>

segue o link com os fontes do exemplo

http://www.baixa.la/arquivo/672509

espere que ajude abraço!

Link para o comentário
Compartilhar em outros sites

  • 0

valeu amigao ajudou muito consegui resolver parte doque quero achei nesses site como mover uma div com o mouse:

http://stackoverflow.com/questions/3263374...se-co-ordinates

http://jsbin.com/ovape/3

quem quiser o mesmo segue o código abaixo:

<html> 


<!--

  Created using http://jsbin.com
  Source can be edited via http://jsbin.com/ovape/edit

-->

  <head> 
    <title>neuro[tile]</title> 
     <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
     <script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
    
    <style type="text/css"> 
      body { margin: 0; }
      div#menu { position: absolute; top: 0px; left: 0; width: 100%; height: 50px; background-color: #666; border-bottom: 1px solid #000; }
      div#map-container { width: 100%; height: 100%; min-height: 100%; margin: 0 auto; text-align: center; }
      div#map { width: 800px; height: 400px; min-height: 400px; background-image: url(http://www.project-vanquish.co.cc/gridtest/grid.jpg); padding: 0px; margin: 0 auto; margin-top: 75px; }
      div#character { top: 0px; left: 0px; width: 38px; height: 38px; min-height: 38px; border: 1px solid #666; background-color: #aaa; opacity:0.5; float: left; }
      div#footer { position: absolute; bottom: 0px; left: 0; width: 100%; height: 50px; background-color: #666; border-bottom: 1px solid #000; }
    </style> 
  </head> 
  <body> 
    <div id="menu">Menu</div> 
    <div id="map-container"> 
      <div id="map"> 
        <div id="character"></div> 
      </div> 
    </div> 
    <div id="footer">Footer</div> 
  <script>      $(function() {
        $("#character").draggable({ grid: [40, 40], containment: '#map' });
      });

      $(document).ready(function() {        
        $(document).bind('keydown',function(e){ 
          switch(e.which) {
            case 37:  $('#character').animate({
                    left:  '-=40'
                  }, 150, function() {

                  });
                  break;
            case 39:  $('#character').animate({
                    left:  '+=40'
                  }, 150, function() {
                  
                  });
                  break;
            case 38:  $('#character').animate({
                    top:  '-=40'
                  }, 150, function() {
                  
                  });
                  break;
            case 40:  $('#character').animate({
                    top:  '+=40'
                  }, 150, function() {
                  
                  });
                  break;
          }
        });
        var mapTop     = $('#map').offset().top;
        var mapLeft    = $('#map').offset().left;
        var charWidth  = $('#character').outerWidth();
        var charHeight = $('#character').outerHeight();

          $('#map').click(function(e) {
            var mouseX = e.pageX - mapLeft - (charWidth/2);  // convert absolute cooridnates
            var mouseY = e.pageY - mapTop  - (charHeight/2); // into relative ones...
            mouseX = Math.round(mouseX/40)*40;
            mouseY = Math.round(mouseY/40)*40;
            $('#character').animate({
              top:  mouseY,
              left:  mouseX
            })
          });
      });</script><script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-1656750-13");
pageTracker._trackPageview();
</script><script src="/js/render/edit.js"></script>
</body> 
</html>

agora so falta fazer uma conexao com o servidor alguém sabe como fazer estava usando um servidor de html5 socket agora estou usando o jwebsocket quem quiser usar é só baixar ele é totalmente gratis segue o site:

http://jwebsocket.org/

valeu e ate +

Editado por ktinho
Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152k
    • Posts
      651,8k
×
×
  • Criar Novo...