DataTransfer: effectAllowed 屬性
DataTransfer.effectAllowed 屬性指定允許的拖放操作的效果。copy 操作用於指示正在拖動的資料將從其當前位置複製到放置位置。move 操作用於指示正在拖動的資料將被移動,而 link 操作用於指示將在源位置和放置位置之間建立某種形式的關係或連線。
此屬性應在 dragstart 事件中設定,以設定拖動源所需的拖動效果。在 dragenter 和 dragover 事件處理程式中,此屬性將被設定為在 dragstart 事件期間分配的任何值,因此 effectAllowed 可用於確定允許哪種效果。
在 dragstart 事件以外的其他事件中為 effectAllowed 賦值沒有效果。
值
一個表示允許的拖放操作的字串。可能的值有:
none-
無法放置該項。
copy-
可以在新位置建立源項的副本。
copyLink-
允許複製或連結操作。
copyMove-
允許複製或移動操作。
link-
可以建立指向新位置源的連結。
linkMove-
允許連結或移動操作。
move-
可以將一項移動到新位置。
all-
允許所有操作。
uninitialized-
當效果未設定時的預設值,等同於 all。
為 effectAllowed 賦值任何其他值都沒有效果,並且會保留舊值。
示例
設定 effectAllowed
在此示例中,我們在 dragstart 處理程式中將 effectAllowed 設定為 "move"。
HTML
html
<div>
<p id="source" draggable="true">
Select this element, drag it to the Drop Zone and then release the selection
to move the element.
</p>
</div>
<div id="target">Drop Zone</div>
<pre id="output"></pre>
<button id="reset">Reset</button>
CSS
css
div {
margin: 0em;
padding: 2em;
}
#source {
color: blue;
border: 1px solid black;
}
#target {
border: 1px solid black;
}
#output {
height: 100px;
overflow: scroll;
}
JavaScript
js
function dragstartHandler(ev) {
log(`dragstart: effectAllowed = ${ev.dataTransfer.effectAllowed}`);
// Add this element's id to the drag payload so the drop handler will
// know which element to add to its tree
ev.dataTransfer.setData("text", ev.target.id);
ev.dataTransfer.effectAllowed = "move";
}
function dropHandler(ev) {
log(`drop: effectAllowed = ${ev.dataTransfer.effectAllowed}`);
ev.preventDefault();
// Get the id of the target and add the element to the target's DOM
const data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
function dragoverHandler(ev) {
log(`dragover: effectAllowed = ${ev.dataTransfer.effectAllowed}`);
ev.preventDefault();
}
const source = document.querySelector("#source");
const target = document.querySelector("#target");
source.addEventListener("dragstart", dragstartHandler);
target.addEventListener("dragover", dragoverHandler);
target.addEventListener("drop", dropHandler);
function log(message) {
const output = document.querySelector("#output");
output.textContent = `${output.textContent}\n${message}`;
output.scrollTop = output.scrollHeight;
}
const reset = document.querySelector("#reset");
reset.addEventListener("click", () => document.location.reload());
結果
規範
| 規範 |
|---|
| HTML # dom-datatransfer-effectallowed-dev |
瀏覽器相容性
載入中…