You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测量单词到右侧页边距的距离并优化连字符换行逻辑

示例
这就是我需要测量的距离。

我为什么需要它?

//↓↓↓↓↓↓↓↓ No ‑ breaking hypen
.replace(/\b((\w+?)\-)((\w+?\b[\.\,\?\!\”\)\:\;]*)(\-(\w+?\b[\.\,\?\!\”\)\:\;]*))?)/g, (_, a,b,c,d,e,f)=>{

const [aaaaaaa,niunumber] = /([\d\.]+(px|em|rem|pt|pc|cm|mm|in|\%|ch|vh|vw|vmin|vmax|ex))/.exec(getComputedStyle(document.body,null).getPropertyValue("font-size"));
const can = document.createElement("canvas");
const ctx = can.getContext("2d");
const ttext = _;
const sWidth = +window.innerWidth;
ctx.font = niunumber + " " + "Serif";
const leength = ctx.measureText(ttext).width;
const ggh = 26 ;//% of screenWidth allowed//max value: 100//
const wordWidth= sWidth * (ggh/100);
    const wtot2 = parseInt(c.length);
    const wtot3 = parseInt(d.length);
    const wtot4 = wtot2 - wtot3;
    if(wtot4 > 0 && leength < wordWidth + 0.01)
        return `${b}\‑${d}\‑${f}`;
    else
        if(leength < wordWidth + 0.01 && wtot4 === 0)
            return `${b}\‑${d}`;
        else
            return `${_}`;
})
//↑↑↑↑↑↑↑↑
;

这是我编写的脚本,用于定位带连字符的单词,并将占据屏幕宽度比例低于设定值的单词替换为非断字连字符。我想了解测量图中该空白距离的方法,以便基于单词到右侧页边距的距离实现换行,效果如下方图片所示:

示例2

图中单词“grotto-”处于我设定的限制范围内(屏幕宽度的26%以内),我希望让它自动换行,请问该如何实现?

内容的提问来源于stack exchange,提问作者bobby324

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 17:02:15