gpt4 book ai didi

javascript - mousedown div 包含到父级(最新)

转载 作者:行者123 更新时间:2023-11-30 06:37:04 24 4
gpt4 key购买 nike

我的内部 div 应该随着鼠标光标在 mousemove 上移动,但我希望它在 if 语句处停止,如果它正在使用 isDragging 变量拖动,这样它会平滑地拖动,但它似乎不会停止任何建议和帮助将不胜感激更新: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;
}

最佳答案

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

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);
}
});

关于javascript - mousedown div 包含到父级(最新),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13773331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com