JavaScript 获取选中文字
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>获取选中文字</title>
    </head>
    <body>
        <input id="inputText" onselect="logSelection(event)">
        <button onclick="obtain()">获取</button>
        <p>被选中的文字为:<span id="selectedText"></span></p>
        <script>
            var selectedText = "";
            var selectionInfo = {
                x: 0,
                y: 0
            };
            function logSelection(event) {
                const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
                selectedText = selection;
                selectionInfo = {
                    x: event.target.selectionStart,
                    y: event.target.selectionEnd
                };
            }
            function obtain() {
                document.querySelector("#selectedText").innerText = selectedText;
                document.getElementById("inputText").focus();
            }
        </script>
    </body>
</html>

运行后在输入框中输入文字,并且选中一段文字,点击获取后会在下面显示选中的文字。

变量 selectedText 用于存储选中文字,selectionInfo 用于存储开始和结束位置。

logSelection 函数用于处理输入框中的文本被选中的事件,首先获取选中的文字,然后更新变量 selectedTextselectionInfo 的值。obtain 函数用于将选中的文字显示在页面上,并将焦点返回到输入框。

在没有特别声明的情况下,内容均为原创,请遵守CC BY-NC-SA 4.0版权协议!
暂无评论

发送评论 编辑评论

注意事项:
  1. 请遵守法律,友善发言。
  2. 评论被回复后没有提醒,请自行关注,敬请见谅。
  3. 无关的内容请移步留言板。
  4. 支持Markdown,可以使用第三方图床插入图片。

				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
呼呼
上一篇
下一篇