제이쿼리:변수는 NaN을 반환합니다.
문제
아래 코드 때문에 겁을 먹지 마세요..질문은 정말 간단합니다. 단 두 줄만 문제를 일으키고 있습니다.
내 코드에서 NaN 오류 코드가 생성되는 이유는 무엇입니까?요소의 위치가 정확하도록 하나의 변수 값을 다른 변수 값에서 빼려고 합니다.
변수는 어쨌든 정수로 간주되는 jQuery position()에서 값을 가져옵니다.
다음 줄을 확인하세요.
// For some reason NaN error code gets generated when line below gets executed.
var posTop = Startpos.top - Stoppos.top;
var posLeft = Startpos.left - Stoppos.left;
전체 코드:
<!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" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
<title>Drag drop 1</title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.1.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var Startpos = new Array;
var Stoppos = new Array;
// Make images draggable.
$(".item").draggable({
// Elements cannot go outside #container
containment: 'parent',
// Make sure the element can only be dropped in a grid.
grid: [150,150],
// Find original position of dragged image.
start: function(event, ui) {
// Make sure picture always are on top when dragged (z-index).
$(this).css({'z-index' : '100'});
// Show start dragged position of image.
Startpos = $(this).position();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
},
// Find position where image is dropped.
stop: function(event, ui) {
// Revert to default layer position when dropped (z-index).
$(this).css({'z-index' : '10'});
// Show dropped position.
Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
}
});
$(".item").droppable({
drop: function(event, ui) {
// Dragged image gets swapped with dropped on image.
var prev_position = "#" + $(this).attr('id');
// For some reason NaN error code gets generated when line below gets executed.
var posTop = Startpos.top - Stoppos.top;
var posLeft = Startpos.left - Stoppos.left;
// Below variables will work. But unfortunately they
// doesn't give the correct numbers for the purpose.
// var posTop = Startpos.top;
// var posLeft = Startpos.left;
$(prev_position).css({'top' : posTop, 'left' : posLeft});
$("div#test").text("Passed variables. Top: " + posTop + " left: " + posLeft);
}
});
});
</script>
<style>
body {
}
#container {
position:relative;
width:480px;
border:1px solid #000;
}
.item {
position:relative;
width:150px;
height:150px;
z-index:10;
}
</style>
</head>
<body>
<div id="container">
<img id="productid_1" src="images/pic1.jpg" class="item" alt="" title="" /><img id="productid_2" src="images/pic2.jpg" class="item" alt="" title="" /><img id="productid_3" src="images/pic3.jpg" class="item" alt="" title="" /><img id="productid_4" src="images/pic4.jpg" class="item" alt="" title="" /><img id="productid_5" src="images/pic5.jpg" class="item" alt="" title="" /><img id="productid_6" src="images/pic6.jpg" class="item" alt="" title="" /><img id="productid_7" src="images/pic7.jpg" class="item" alt="" title="" /><img id="productid_8" src="images/pic8.jpg" class="item" alt="" title="" /><img id="productid_9" src="images/pic9.jpg" class="item" alt="" title="" />
</div>
<div style="clear:both;"></div>
<div id="start">Waiting...</div>
<div id="stop">Waiting...</div>
<div id="hover">Waiting...</div>
<div id="stop2">Waiting...</div>
<div id="test">Waiting...</div>
</body>
</html>
해결책
문제는 droppable.drop()이 호출된다는 것입니다. ~ 전에 draggable.stop().따라서 Stoppos는 아직 계산되지 않았습니다.
이를 처리하는 한 가지 방법은 드래그되는 항목을 추적하고 droppable.drop()에서 해당 항목의 위치를 계산하는 것입니다.예를 들어(코드의 하위 집합) "Dragging" 개체를 확인하세요.
$(document).ready(function() {
var Startpos = new Array;
var Stoppos = new Array;
var Dragging = null;
// Make images draggable.
$(".item").draggable({
// Elements cannot go outside #container
containment: 'parent',
// Make sure the element can only be dropped in a grid.
grid: [150,150],
// Find original position of dragged image.
start: function(event, ui) {
Dragging=this;
// Make sure picture always are on top when dragged (z-index).
$(this).css({'z-index' : '100'});
// Show start dragged position of image.
Startpos = $(this).position();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
},
// Find position where image is dropped.
stop: function(event, ui) {
// Revert to default layer position when dropped (z-index).
$(this).css({'z-index' : '10'});
// Show dropped position.
Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
Dragging=null;
}
});
그러나 이 문제를 해결할 수 있는 다른 합법적인 방법이 여러 가지 있을 수 있습니다.
다른 팁
내가 아는 한 위치 ()는 jQuery 함수가 아닙니다.
대신 시도해보십시오.
Startpos = $(this).offset();
그런 다음 상단 및 왼쪽 속성에 액세스 할 수 있어야합니다.
이것들이 문제를 일으키는 선이라고 확신합니까? -
"var postop = startpos.top -stoppos.top;"
유효한 정수/이중 값을 Postop에 반환합니까? 나는 지난 주에 내 프로젝트 중 하나를 코딩하고 있었고 같은 NAN 문제가 있었는데, 그 가치를 정수에게 구문 분석하려고 노력했고 그것은 효과가있었습니다.
수학적 계산을하고 있기 때문에 값을 빼기 전에 값을 두 배로 구문 분석 해보십시오.
때로는 솔루션이 매우 간단하고 우리는 그것을 과도하게 복잡하게 만드는 경향이 있습니다.
구문 분석이 작동하지 않으면 배열에서 올바른 값을 전달하지 않을 수 있습니다. STARTPOS [0] .TOP와 같은 것을 시도하십시오
이것이 도움이되기를 바랍니다. 행운을 빕니다!
이 계산을 수행 할 때 STARTPOS 또는 SOPPOS는 여전히 빈 배열 일뿐입니다.
대신 적절한 기본값으로 설정하십시오 (0, 0).
저를 당황하게하는 것은 이것이 효과가 있다는 것입니다.
바꾸다:
var posTop = Startpos.top - Stoppos.top;
var posLeft = Startpos.left - Stoppos.left;
와 함께:
var posTop = Startpos.top;
var posLeft = Startpos.left;
숫자가 내가 원하는 것이 아니더라도 작동합니다. 어떤 이유로 든 간단한 서브 스코프가 유효하지 않은 것 같습니다.
도움을 주셔서 감사합니다 :)
문제를 발견했습니다.
Stoppos = $(this).position();
안에는 안됩니다 :
$(".item").draggable({
stop: function(event, ui) {
그러나 대신 :
$(".item").droppable({
drop: function(event, ui) {
완전한 코드 :
<!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" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
<title>Drag drop 1</title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.1.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var Startpos = null;
var Stoppos = null;
// Make images draggable.
$(".item").draggable({
// Elements cannot go outside #container
containment: 'parent',
// Make sure the element can only be dropped in a grid.
grid: [150,150],
// Find original position of dragged image.
start: function(event, ui) {
// Make sure picture always are on top when dragged (z-index).
$(this).css({'z-index' : '100'});
// Show start dragged position of image.
Startpos = $(this).position();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
},
// Find position where image is dropped.
stop: function(event, ui) {
// Revert to default layer position when dropped (z-index).
$(this).css({'z-index' : '10'});
}
});
$(".item").droppable({
drop: function(event, ui) {
// Dragged image gets swapped with dropped on image.
var prev_position = "#" + $(this).attr('id');
Stoppos = $(this).position();
var posTop = Startpos.top - Stoppos.top;
var posLeft = Startpos.left - Stoppos.left;
$(prev_position).css({'top' : posTop, 'left' : posLeft});
// Test window
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
$("div#test").text("Passed variables. Top: " + posTop + " left: " + posLeft);
}
});
});
</script>
<style>
body {
}
#container {
position:relative;
width:480px;
border:1px solid #000;
}
.item {
position:relative;
width:150px;
height:150px;
z-index:10;
}
</style>
</head>
<body>
<div id="container">
<img id="productid_1" src="images/pic1.jpg" class="item" alt="" title="" /><img id="productid_2" src="images/pic2.jpg" class="item" alt="" title="" /><img id="productid_3" src="images/pic3.jpg" class="item" alt="" title="" /><img id="productid_4" src="images/pic4.jpg" class="item" alt="" title="" /><img id="productid_5" src="images/pic5.jpg" class="item" alt="" title="" /><img id="productid_6" src="images/pic6.jpg" class="item" alt="" title="" /><img id="productid_7" src="images/pic7.jpg" class="item" alt="" title="" /><img id="productid_8" src="images/pic8.jpg" class="item" alt="" title="" /><img id="productid_9" src="images/pic9.jpg" class="item" alt="" title="" />
</div>
<div style="clear:both;"></div>
<div id="start">Waiting...</div>
<div id="stop">Waiting...</div>
<div id="hover">Waiting...</div>
<div id="stop2">Waiting...</div>
<div id="test">Waiting...</div>
</body>
</html>
이제 이미지가 한 번 이상 움직일 때 바로 이미지의 배치를 얻는 방법을 알아 내야합니다. 위치 : 상대는 Draggables에 자동으로 추가되고 위치를 계산하는 데 문제가됩니다.