Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   перетаскивание объекта по координатам Y (https://javascript.ru/forum/misc/63615-peretaskivanie-obekta-po-koordinatam-y.html)

korih 18.06.2016 13:38

перетаскивание объекта по координатам Y
 
Добрый день всем.

Встретился с неприятностью перетаскивания элемента.

моя писанина к сожалению работает не совсем так как я себе это представлял. при нажатии на элемент и ведением мышки вверх-вниз, элемент переносится только вниз, но вверх почему-то не хочет(


var client;

$("#auth").mousedown(function() {
	client = true
	$(this).mousemove(function(event) {
	var clientCoords = event.clientY;
	if(client == true){
	$("#auth").css({marginTop: clientCoords});
	}
	});

});
$(this).mouseup(function() {
	client = false;
});

рони 18.06.2016 13:51

korih,
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
    .hot{
         border: 1px dashed Gray; padding: 5px; height: 100px; width: 100px
    }

  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  <script>
$(function() {
    var client;
    $("#auth").mousedown(function() {
        client = true
    });
    $("body").mouseup(function() {
        client = false
    }).mousemove(function(event) {
        var clientCoords = event.clientY - $("#auth").height() / 2;
        if (client == true) $("#auth").css({
            marginTop: clientCoords
        })
    })
});
  </script>
</head>

<body>

 <div class="hot" id="auth"></div>

</body>
</html>

korih 18.06.2016 13:54

спасибо, только вот хотел написать, что додумал проблему, он делал отступ к началу координат)

$(".box").mousedown(function() {
	client = true
	$(this).mousemove(function(event) {
	var clientCoords = event.clientY;
	if(client == true){
	$(this).css({top: clientCoords/2});
	}
	});

});
$(this).mouseup(function() {
	client = false;
});

Decode 18.06.2016 15:52

рони, у тебя при mousemove, если взять блок за край – он резко прыгает центром под курсор мыши.

Decode 18.06.2016 15:54

<style>
	.hot {
		border: 1px dashed gray;
		padding: 5px;
		height: 100px;
		width: 100px;
		cursor: pointer;
	}
</style>

<div class="hot" id="auth"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<script>
	$(function() {
		var client;
		var shiftY;

		$('#auth').mousedown(function() {
			client = true;
			shiftY = event.clientY - ( $('#auth').offset().top - $(window).scrollTop() );
		});

		$('body').mouseup(function() {
			client = false;
		}).mousemove(function(event) {
			var clientCoords = event.clientY - shiftY;

			if (client == true) {
				$('#auth').css({
					marginTop: clientCoords
				});
			}
		});
	});
</script>

korih 18.06.2016 17:03

а что бы так же ровно было и по левой стороне (кружить по всей странице в итоге), то так будет?

var client;
        var shiftY;
        var shiftX;
 
        $('.box').mousedown(function(event) {
            client = true;
            shiftY = event.clientY - ( $('.box').offset().top - $(window).scrollTop() );
            shiftX = event.clientX - ( $('.box').offset().left - $(window).scrollLeft() );
        });
 
        $('body').mouseup(function() {
            client = false;
        }).mousemove(function(event) {
            var clientCoordsY = event.clientY - shiftY;
            var clientCoordsX= event.clientX - shiftX;

 
            if (client == true) {
                $('.box').css({
                    marginTop: clientCoordsY,
                    marginLeft: clientCoordsX
                });
            }
        });

рони 18.06.2016 17:40

korih,
https://learn.javascript.ru/drag-and-drop

https://learn.javascript.ru/drag-and-drop-objects

http://jqueryui.com/draggable/

Rasy 18.06.2016 23:57

Перетаскивание объекта
 
<body>

<style>
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.square {
  position: relative;
  top: 0;
  
  box-sizing: border-box;
  width: 150px;
  height: 150px;
  padding: 10px;
  
  cursor: move;
  
  color: white;
  background: coral;
}

.square:active {
  transform: rotate3d(-1, 1, 0, 10deg);
}
</style>

<script data-require="jquery@3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>

<div class="square"></div>

<script>
  init('.square');
  
  function init(elem) {
    var 
      $square = $(elem),
      press = false,
      ofsY,
      ofsX;
    
    $square.on('mousedown mouseup mouseleave', function(event) {
      press = pressState(event);
      
      ofsY = event.pageY - $square.offset().top;
      ofsX = event.pageX - $square.offset().left;
    });
    
    function pressState(event) {
      if (event.type === 'mousedown') {
        return true;
      }
      return false;
    }
  
    $('body').mousemove(function(event) {
      $square.html('y: ' + event.pageY + ' x: ' + event.pageX);
  
      if (press) {
        $square.css({
          'margin-top': event.pageY - ofsY,
          'margin-left': event.pageX - ofsX
        });
      }
      
    });
  }
</script>

</body>

korih 19.06.2016 03:32

:yes: :thanks:


Часовой пояс GMT +3, время: 12:21.