在范围之间传输变量值

时间:2014-08-18 07:23:33

标签: javascript jquery scope position draggable

我生病了,厌倦了思考。好的,有一个可拖动的蓝色盒子,如果它接触到红色框,则红框突然随机改变位置。我知道,我混淆了整个代码;我对这个编码部分非常愚蠢。但我无法想象它的错误。我需要有人了解这种情况。

Jquery Part。

$(document).ready(function() {
var kol = 253;
var score = 0;
var redBoxWidth = $('#redBox').width();
var redBoxHeight = $('#redBox').height();
var redT = $('#redBox').position().top;
var redL = $('#redBox').position().left;
var redBox = $(".redBox");

var blueCoordinates = function(element1) {
    var top;
    var left;
    var blueBoxWidth = $('#blueBox').width();
    var blueBoxHeight = $('#blueBox').height();
    element1 = $(element1);
    top = element1.position().top;
    left = element1.position().left;

    $('#results').text('X: ' + left + ' ' + 'Y: ' + top);
    $('#results3').text('redL: ' + redL + 'redX: ' + redT);
    setTimeout(function() {
        if ((top > (redX) && left > (redY))) {
            setTimeout(function() {
                $('#results2').text(top + "  " + redX + "  " + redY + "  " + redBoxHeight + "   " + redBoxWidth);
            });
            redX = (Math.random() * ($('#canvas').width() - redBoxWidth)).toFixed();
            redY = (Math.random() * ($('#canvas').height() - redBoxHeight)).toFixed();
            redBox.css({
                'position': 'absolute',
                'left': redX + 'px',
                'top': redY + 'px'

            });


        }
        blueCoordinates();
    });
}

$('#blueBox').draggable({
    drag: function() {
        blueCoordinates('#blueBox');
    }
});

});

HTML PART

<div id="canvas">
<div id="blueBox"></div>
<div id="redBox" class="redBox"></div>
</div>
<div id="results" class="results"></div>
<div id="results1" class="results"></div>
<div id="results2" class="results"></div>
<div id="results3" class="results"></div>

CSS PART

#
canvas {
width: 500px;
height: 400px;
background: #ccc;
position: absolute;
top: 0px;
left: 0px;
}#
blueBox {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
background: blue;
cursor: move;
}
.redBox {
position: absolute;
top: 250px;
left: 350px;
width: 100px;
height: 100px;
background: red;
cursor: move;
}
.results {

text - align: center;
position: relative;
top: 400px;
left: 25px;
}

1 个答案:

答案 0 :(得分:0)

我只需要将reduX和readY的值传递给resT和red Ep>

 if ((top > (redX) && left > (redY))) {
        setTimeout(function() {
            $('#results2').text(top + "  " + redX + "  " + redY + "  " + redBoxHeight + "   " + redBoxWidth);
        });
        redX = (Math.random() * ($('#canvas').width() - redBoxWidth)).toFixed();
        redY = (Math.random() * ($('#canvas').height() - redBoxHeight)).toFixed();
      redT=redY;
      redL=redX;
        redBox.css({
            'position': 'absolute',
            'left': redX + 'px',
            'top': redY + 'px'

        });