gpt4 book ai didi

javascript - 将文本从一个 INPUT 拖动到另一个 INPUT,而不从源 INPUT 中删除文本

转载 作者:行者123 更新时间:2023-11-30 21:20:28 29 4
gpt4 key购买 nike

我有两个文本输入元素 A 和 B。

我希望用户能够从 A 中选择部分或全部文本并拖动到 B,但文本不会从 A 中消失。

假设“A”包含“quick brown fox”,用户突出显示“fox”一词并将其拖到“B”。默认情况下,框“A”现在包含“quick brown”,但我希望它仍然显示“quick brown fox”。

我不希望“A”是只读的。

最佳答案

function preventDragNDropChangesOn(inputElement) {
let previousValue = inputElement.value
let isDragged = false
let wasDropped = false

/*
* event order:
* dragstart (prepare for possible text cutting)
* drop (input text was not cut out yet at this point, save it to revert it later)
* change (input text is already cut out at this point - revert it to the previous value)
* dragend (set variables to initial state)
*/

inputElement.addEventListener('dragstart', () => isDragged = true)
document.body.addEventListener('drop', () =>
(wasDropped = isDragged) && (previousValue = inputElement.value))
inputElement.addEventListener('change', (e) =>
isDragged && wasDropped && (e.target.value = previousValue))
inputElement.addEventListener('dragend', () => isDragged = wasDropped = false)
}

const inputElement = document.querySelector(".js-controlled-input")

preventDragNDropChangesOn(inputElement)

function preventDragNDropChangesOn(inputElement) {
let previousValue = inputElement.value
let isDragged = false
let wasDropped = false
let shouldRevertChanges = () => isDragged && wasDropped

document.body.addEventListener('drop', () => wasDropped = isDragged)
inputElement.addEventListener('dragstart', () => isDragged = true)
inputElement.addEventListener('dragend', () => (isDragged = false) || (wasDropped = false))
inputElement.addEventListener('input', (e) =>
shouldRevertChanges()
? (e.target.value = previousValue)
: (previousValue = e.target.value)
)
}
<input class="js-controlled-input" value="quick brown fox"/>
<input class="js-target"/>

https://jsfiddle.net/91o9mpaz/4/


IE11兼容方案:

function preventDragNDropChangesOn(inputElement) {
let previousValue = inputElement.value
inputElement.addEventListener('dragstart', function () { previousValue = inputElement.value })
inputElement.addEventListener('dragend', function () { setTimeout(function() {inputElement.value = previousValue }, 1) })
}

关于javascript - 将文本从一个 INPUT 拖动到另一个 INPUT,而不从源 INPUT 中删除文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45235857/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com