Movable div没有jQuery UI [英] Movable div without jQuery UI
问题描述
其实我想要完成的只是通过点击顶部的div可以拖动窗口(如下图)
function endMove(){
$(本).removeClass( '移动');
}
函数startMove(){
$('。可移动')mousemove(function(event){
var thisX = event.pageX - $(this) ()/ 2,
thisY = event.pageY - $(this).height()/ 2;
$('。movable')。 :thisX,
top:thisY
});
});
}
$(document).ready(function(){
$(#containerDiv)。click(function(){
$(this).addClass可移动');
startMove();
})。mouseup(function(){
$(this).removeClass('movable');
endMove();
});
});
如果您的div被布局,那么有一个容器将标题和内容区域嵌套在内部,那么我认为您可以进行以下更改将点击处理绑定到标题,但将移动应用于容器。此外,您需要捕获点击的初始位置,并计算您的移动增量,从那里开始,以避免导致div跳转:
var x = 0,y = 0;
$(document).ready(function(){
$('。moving')。live('mousemove',function(event){
var deltaX = event.pageX - x ,
deltaY = event.pageY - y;
x = event.pageX;
y = event.pageY;
var movable = $('可移动的');
可移动的({
left:moving.offset()。left + deltaX,
top:moving.offset()。top + deltaY
}) ;
});
$(#headerDiv)
.mousedown(function(event){
x = event.pageX;
y = event .pageY;
$(this).parent()。addClass('movable');
})
.mouseup(function(){
$(this) ().removeClass('moving');
});
});
我没有彻底测试,但在快速测试页上似乎工作得很好。
I have an application which lets the user open several draggable popups. I don't want to use jQuery UI and below is the code so far. However, when dragging a div it gets centered to the pointer, and that's not how it should be done.
Actually, what I want to accomplish is that it should only be able to drag the window by clicking on the top div (se illustration below).
function endMove() {
$(this).removeClass('movable');
}
function startMove() {
$('.movable').mousemove(function(event) {
var thisX = event.pageX - $(this).width() / 2,
thisY = event.pageY - $(this).height() / 2;
$('.movable').offset({
left: thisX,
top: thisY
});
});
}
$(document).ready(function() {
$("#containerDiv").click(function() {
$(this).addClass('movable');
startMove();
}).mouseup(function() {
$(this).removeClass('movable');
endMove();
});
});
If your divs are laid out so there is a container with a header and a content area nested inside then I think you could make the following changes to bind the click handling to the header but apply the movement to the container. Also, you need to capture the initial location of the click and calculate your movement deltas starting from there in order to avoid causing the div to jump:
var x = 0, y = 0;
$(document).ready(function() {
$('.movable').live('mousemove', function(event) {
var deltaX = event.pageX - x,
deltaY = event.pageY - y;
x = event.pageX;
y = event.pageY;
var movable = $('.movable');
movable.offset({
left: movable.offset().left + deltaX,
top: movable.offset().top + deltaY
});
});
$("#headerDiv")
.mousedown(function(event) {
x = event.pageX;
y = event.pageY;
$(this).parent().addClass('movable');
})
.mouseup(function() {
$(this).parent().removeClass('movable');
});
});
I haven't tested this thoroughly, but it seems to work pretty well in a quick test page.
这篇关于Movable div没有jQuery UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!