V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
edis0n0
V2EX  ›  程序员

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

  •  
  •   edis0n0 · 2022-11-14 02:11:13 +08:00 · 1004 次点击
    这是一个创建于 553 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    4 条回复    2022-11-14 09:26:32 +08:00
    edis0n0
        1
    edis0n0  
    OP
       2022-11-14 02:13:59 +08:00
    discord 上的群友给我推荐了个库 https://github.com/accursoft/caret 明天试下 暂时结帖
    ragnaroks
        3
    ragnaroks  
       2022-11-14 09:21:00 +08:00   ❤️ 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  
       2022-11-14 09:26:32 +08:00
    自己试了下手机上不点是没有 foucs 的,PC 上似乎也不是所有浏览器都可以做到,还是用你找到的那个库吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1670 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:05 · PVG 08:05 · LAX 17:05 · JFK 20:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.