2014-02-10 21 views
11

似乎在將某個輸入元素放入具有draggable =「true」的元素中時,輸入元素會失去很多功能。這似乎只發生在Firefox。防止拖動事件干擾Firefox中的輸入元素使用HTML5拖放操作

見我的jsfiddle: http://jsfiddle.net/WC9Fe/3/

HTML:

<div id="drag" draggable="true"> 
    Drag this div <br /> 
    <input id="message" type="text" /> 
</div> 
<div id="drop"> 
    Drop area 
</div> 

JS:

$('#drag').on('dragstart', function(e){ 
    e.originalEvent.dataTransfer.setData('Text', $('#message').val()); 
    e.originalEvent.dataTransfer.effectAllowed = 'move'; 
}); 

var drop = $('#drop'); 
drop.on('dragover', function(e){ 
    e.preventDefault(); 
}); 
drop.on('dragenter', function(e){ 
    e.preventDefault(); 
}); 
drop.on('drop', function(e){ 
    alert('Target succesfully dropped: ' + e.originalEvent.dataTransfer.getData('Text')); 
    e.preventDefault(); 
}); 

現在儘量選擇使用Firefox瀏覽器輸入文字。似乎不可能。在IE/Chrome中嘗試一樣。似乎工作得很好。

+0

這個問題在IE中也是可以觀察到的...... IE 11.0.9600要精確.. – Paritosh

回答

12

據我所知這是FF中的一個已知錯誤。一個快速的(和「髒的」解決方法)將刪除文本輸入focus事件的draggable屬性,在文本輸入blur事件上再次添加它,並禁用#drag div上的文本選擇,以便在單擊焦點之外時啓用拖動輸入(直接點擊#div)。

更新提琴here

示例代碼:

JS:

$('#message') 
    .on('focus', function(e) { 
     $(this).closest('#drag').attr("draggable", false); 
    }) 
    .on('blur', function(e) { 
     $(this).closest('#drag').attr("draggable", true); 
    }); 

CSS:

.disable-selection { 
    /* event if these are not necessary, let's just add them */ 
    -webkit-user-select: none; 
    -ms-user-select: none; 
    user-select: none; 

    /* this will add drag availability once you clicked the 
     #drag div while you're focusing #message div */ 
    -moz-user-select: none; 
} 

希望它可以幫助你。

+0

謝謝!一個骯髒的解決方法確實...至於現在:我從可拖動區域中刪除了輸入元素,因爲我沒有在所有瀏覽器中實現所需的效果(IE8仍然是一個問題)。 你會反對使用HTML5拖放和使用JQuery UI拖放嗎? – nicojs

+1

你可以通過閱讀更多的信息:[HTML5拖放的優點,而不是jQuery UI拖放](http://stackoverflow.com/questions/9524543/advantages-of-html-5-drag-and-drop- jquery-ui-drag-and-drop)和[html5 vs jquery ui拖放](http://stackoverflow.com/questions/6920741/html5-vs-jquery-drag-and-drop)。如果您需要定位各種瀏覽器(舊版瀏覽器),如果您不想遇到麻煩,並且時間不夠,我推薦使用jQuery UI拖放。 –

5

請參閱Firefox defect

作爲一種替代方法,在輸入焦點事件上設置draggable =「false」,並在輸入模糊事件中替換回draggable =「true」。對於沒有任何框架的示例,請參閱jsfiddle

HTML:

<div draggable="true" id="draggableDiv"> 
    <textarea onfocus="onFocus();" onblur="onBlur();">Inside draggable (FIXED)</textarea> 
</div> 

JS:

onFocus= function(e) { 
    document.getElementById("draggableDiv").setAttribute("draggable", "false"); 
} 
onBlur= function(e) { 
    document.getElementById("draggableDiv").setAttribute("draggable", "true"); 
} 
0

我用textarea的所述OnMouseEnter在和OnMouseLeave在函數來設置在div拖動只有當鼠標textarea的外部。

我這樣做是因爲我需要將焦點留在編輯字段中,而拖動和拖動本身不會觸發焦點事件。

0

我也發現使用onmouseenter和onmouseleave切換可拖動屬性的效果更好,因爲它將光標置於實際單擊的輸入框中。當使用onfocus/onblur時,即使在中間單擊,光標也會始終移至文本的開頭或結尾。