gpt4 book ai didi

javascript - 使用javascript输出选定的文本

转载 作者:行者123 更新时间:2023-11-29 16:31:32 25 4
gpt4 key购买 nike

我已经为整个文档添加了一个事件监听器。然而,奇怪的事情正在发生。选择时仅显示输入字段中的文本。当我在 <p> 中选择文本时没有任何反应标签

<!DOCTYPE html>
<html>

<body>

<p>This example uses the addEventListener() method to attach a "select" event to an element.</p>

<input style="width:100%" type="text" value="Only text in the input field is being displayed when selected!" id="myText">

<p id="demo"></p>

<script>
document.addEventListener("select", myFunction);

function myFunction() {
let selection = window.getSelection().toString();
document.getElementById("demo").innerHTML = selection;
}
</script>

</body>

</html>

最佳答案

select 事件仅适用于 input 元素:

根据 MDN :

The event is not available for all elements in all languages. For example, in HTML, select events can be dispatched only on form and elements.

因此,我们也可以使用 mouseup 事件来检查文本选择。

<!DOCTYPE html>
<html>

<body>

<p id="test">This example uses the addEventListener() method to attach a "select" event to an element.</p>

<input style="width:100%" type="text" value="Only text in the input field is being displayed when selected!" id="myText">
<p id="demo"></p>
<script>
document.addEventListener("mouseup", function(){
if(document.getSelection()){
document.querySelector("#demo").textContent = document.getSelection();
}else if(window.getSelection()){
document.querySelector("#demo").textContent = document.getSelection();
}else if(document.selection){
document.querySelector("#demo").textContent = document.selection.createRange().text;
}
});
</script>

</body>

</html>

关于javascript - 使用javascript输出选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55941143/

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