jquery拉拽div

代码提醒:需要导入jquery库


<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="jquery.js"></script>
</head>
<style type="text/css">
       *{
padding: 0;
margin: 0;
}
div{
width: 110px;
height: 120px;
background: pink;
cursor: pointer;
position: absolute;
left: 0;
top: 0;
}
</style>
<script type="text/javascript">
    $(function(){
    //mousedown是相对整个document的而不是相对某个元素的
$('div').mousedown(function(e){
// e.pageX鼠标在document中点下的x轴的位置
//obj.offsetLeft 指 obj (某个选中的元素的左到document左边的位置
var positionDiv = $(this).offset();
var distenceX = e.pageX - positionDiv.left;
var distenceY = e.pageY - positionDiv.top;
//distenceX是鼠标点下的位置到div左边上的位置的距离值
$(document).mousemove(function(e){
//e.pageX这个不是上面那个e.pageX而是鼠标移动的距离;
var x = e.pageX - distenceX;
var y = e.pageY - distenceY;
//if里面的代码是防止出现滚动条
if(x<0){
x=0;
}else if(x>$(document).width()-$('div').outerWidth(true)){
//$('div').outerWidth(true)求出整个div的宽度
//x>$(document).width()-$('div').outerWidth(true)
//这个条件是判断div是否有碰到document的最右边
x = $(document).width()-$('div').outerWidth(true);
}

if(y<0){
y=0;
}else if(y>$(document).height()-$('div').outerHeight(true)){
y = $(document).height()-$('div').outerHeight(true);
}
$('div').css({
'left':x+'px',
'top':y+'px'
});
});
$(document).mouseup(function(){
$(document).off('mousemove');
});
});
});
</script>
<body>
<div></div>
</body>
</html>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现 WPF 中的可控件生成,可以使用拖放操作。以下是一个基本的示例: 首先,在 XAML 中设置一个源控件,允许它被拖动。例如,你可以使用一个 Button 控件,并在 MouseDown 事件处理程序中启动一个拖动操作: ``` <Button Content="Drag Me" MouseDown="Button_MouseDown"/> ``` 在 MouseDown 事件处理程序中,可以使用 DragDrop.DoDragDrop 方法启动拖放操作。此方法需要三个参数:源控件、要传递的数据和拖动操作的类型。例如: ``` private void Button_MouseDown(object sender, MouseButtonEventArgs e) { DragDrop.DoDragDrop((Button)sender, "Some data to drag", DragDropEffects.Copy); } ``` 接下来,在 XAML 中设置一个接收控件,允许它接收拖放的数据。例如,你可以使用一个 StackPanel 控件,并在 Drop 事件处理程序中处理拖放操作: ``` <StackPanel Drop="StackPanel_Drop"/> ``` 在 Drop 事件处理程序中,可以使用 e.Data.GetData 方法获取传递的数据,并创建一个新控件以显示该数据。例如: ``` private void StackPanel_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.StringFormat)) { string data = (string)e.Data.GetData(DataFormats.StringFormat); Button newButton = new Button() { Content = data }; ((StackPanel)sender).Children.Add(newButton); } } ``` 这将在 StackPanel 中添加一个新的 Button 控件,其中包含拖放操作中传递的数据。你可以根据需要自定义此过程,例如,可以使用其他控件作为源控件,将更多数据传递给接收控件等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值