V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
edis0n0
V2EX  ›  程序员

textarea mousemove 事件怎么获取光标所在的字符位置?

  •  
  •   edis0n0 · Nov 14, 2022 · 1467 views
    This topic created in 1260 days ago, the information mentioned may be changed or developed.

    例如 abcdefg 鼠标放在 c 和 d 之间 (不点击!) 要拿到 3 这个 index mousemove 貌似只能拿到坐标,必须自己算吗 因为每个设备字体和缩放都不太一样,textarea 还能滚动,自己算貌似很困难

    4 replies    2022-11-14 09:26:32 +08:00
    edis0n0
        1
    edis0n0  
    OP
       Nov 14, 2022
    discord 上的群友给我推荐了个库 https://github.com/accursoft/caret 明天试下 暂时结帖
    ragnaroks
        3
    ragnaroks  
       Nov 14, 2022   ❤️ 1
    样例代码:
    const flag = '§';
    let index = 0;
    $0.onfoucs(function(event){
    event.target.setRangeText(flag);
    index = event.target.value.indexOf(flag);
    event.target.value.replace(flag,'');
    });

    使用的 flag 应当唯一
    ragnaroks
        4
    ragnaroks  
       Nov 14, 2022
    自己试了下手机上不点是没有 foucs 的,PC 上似乎也不是所有浏览器都可以做到,还是用你找到的那个库吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3283 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 13:21 · PVG 21:21 · LAX 06:21 · JFK 09:21
    ♥ Do have faith in what you're doing.