我正在嘗試創建拖放元素,該元素允許我移動它所連接的元素。一切都在動態創建。我有一個重新發生的問題,我不能從嵌套的函數調用中更改css。jQuery更改嵌套函數調用中的CSS
的jQuery(不工作)
//Drag begin
var dragX;
var dragY;
var mouseDown = false;
var dragIcon = $('<span>')
.css({
'z-index' : '11',
'position' : 'absolute',
'width' : '300px',
'height' : '140px',
'left' : '0px',
'top' : '20px'
})
.addClass('unselectable')
.mousedown(function(){
mouseDown = true;
$(this).mousemove(function(){
if(mouseDown == true){
var dragX = getCurrentMouseX();
var dragY = getCurrentMouseY();
//Don't allow ideas to be created too close to the border of the page
if(dragX < 260){
dragX = 260;
}else if(dragX > window.innerWidth - 260){
dragX = window.innerWidth - 260;
}
if(dragY < 160){
dragY = 160;
} else if(dragY > window.innerHeight - 450){
dragY = window.innerHeight - 450;
}
$(this).css({
'left' : dragX - 150,
'top' : dragY - 81
});
}
})
})
.mouseout(function(){
mouseDown = false;
})
.mouseup(function(){
mouseDown = false;
});
我用JavaScript編寫的函數工作正常,但我試圖將其轉換爲jQuery的。以下是工作的JavaScript函數:
JavaScript的(工作)
//Drag begin
var dragX;
var dragY;
var mouseDown = false;
//TODO: An icon which can be used to drag the cloud around
var dragIcon = document.createElement('span');
dragIcon.style.zIndex = "11";
dragIcon.style.position = "absolute";
dragIcon.style.width = "300px";
dragIcon.style.height = "140px";
dragIcon.setAttribute('class', 'unselectable');
dragIcon.style.left = "0px";
dragIcon.style.top = "20px";
dragIcon.unselectable = "on";
dragIcon.style.MozUserSelect = "none";
dragIcon.onselectstart = function() {return false;}
dragIcon.onmousedown = function(){
mouseDown = true;
dragIcon.onmousemove = function(){
if(mouseDown == true){
var dragX = getCurrentMouseX();
var dragY = getCurrentMouseY();
if(dragX < 260){
dragX = 260;
}else if(dragX > window.innerWidth - 260){
dragX = window.innerWidth - 260;
}
if(dragY < 160){
dragY = 160;
} else if(dragY > window.innerHeight - 450){
dragY = window.innerHeight - 450;
}
cloudStyle.left = dragX - 150 + "px"; //-150 to make up for the position of the drag icon
sunRay.style.left = dragX - 220 + "px";
cloudStyle.top = dragY - 81 + "px"; //-85 to make up for the positioning
sunRay.style.top = dragY - 250 + "px";
}
}
}
dragIcon.onmouseout = function(){
mouseDown = false;
}
dragIcon.onmouseup = function(){
mouseDown = false;
}
能否請你指出我要去哪裏錯了,無論我是採取錯誤的做法。謝謝。
如果你看看JavaScript的等價物,你會發現OP是[創建一個新的元素](http://api.jquery.com/jQuery/#jQuery2)。 –
我的不好,我已經相應地更新了我的答案 – Joey