2

我的内部 div 假设在 mousemove 上用鼠标光标移动,但如果它使用 isDragging 变量拖动,我希望它在 if 语句处停止,因此它会顺利拖动,但它似乎不会停止任何建议和帮助将不胜感激更新:jsFiddle

var yellow = $('#yellow');
var offset = yellow.offset();
var offsetWidth = offset.left + yellow.width();
var offsetHeight = offset.top + yellow.height();
var isDragging = false;

var red = $('#red');

$('#red').hide();

yellow.on('mousedown', function(event) {    
    $('#red').show();  
});
yellow.on('mouseup', function(event) {
    $('#red').hide();        
});
yellow.on('mousemove', function (e) {

    if(e.pageX > offset.left + ($(red).width() / 2) && e.pageX < offsetWidth - ($(red).width() / 2)
        && e.pageY > offset.top + ($(red).height() / 2) && e.pageY < offsetHeight - ($(red).height() / 2) && !isDragging ){
        red.css("left", e.pageX - $(red).width() / 2 );
        red.css("top", e.pageY - $(red).height() / 2);
    }

    $('#red').draggable(
        {'containment':'#yellow',
         start:function(event, ui) {
            isDragging = true;
        },
        drag:function(event, ui) {
            isDragging = true;
        },stop:function(event, ui) {
            isDragging = false;
        }
    });
});


<div id="yellow">
    <div id="red"></div>
</div>

    #yellow {
position: absolute;    
width: 250px; 
height: 250px; 
background-color: Yellow; 
}

#red {
position: absolute;
width: 100px; 
height: 100px; 
background-color: red; 
z-index: 100; 
}
4

1 回答 1

0

我不能说我为这个解决方案感到自豪,但它似乎完成了任务:

http://jsfiddle.net/pPn3v/42/

var yellow = $('#yellow');
var offset = yellow.offset();
var offsetWidth = offset.left + yellow.width();
var offsetHeight = offset.top + yellow.height();

var red = $('#red');

yellow.on('mousemove', function (e) {
    if(e.pageX+red.width() < offsetWidth
      && e.pageY+red.height() < offsetHeight){
        red.css("left", e.pageX);
        red.css("top", e.pageY);
    }
});

red.on('mousemove', function (e) {
    if(e.pageX+red.width() < offsetWidth
      && e.pageY+red.height() < offsetHeight){
        red.css("left", e.pageX);
        red.css("top", e.pageY);  
    }               
});
于 2012-12-08T01:30:43.587 回答