缩放页面时无偏移定位段落特定字符及固定标记位置的实现方法
问题原因
你当前的写法是手动给标记层设置固定px坐标,只要页面缩放、容器宽度变化导致文本换行、系统字体大小调整,目标字符的实际渲染位置就会发生变化,固定坐标自然会偏移。
最优解决方案(无兼容问题,任意缩放都不会偏移)
不要在外层容器下手动定位标记,给需要标记的目标字符单独套一个相对定位的行内标签作为锚点,把圆形标记放在这个锚点标签内部做绝对定位,锚点会跟随文本流自动调整位置,标记自然永远对准目标字符。
修正后可直接运行的代码如下:
<body> <div style="white-space: pre-wrap"> <p> <!-- 给要标记的1套锚点 --> <span style="position: relative;"> <!-- 圆形标记层,相对于锚点定位 --> <span style="position: absolute; top: -5px; left: -8px; height: 25px; width: 25px; border-radius: 50%; border: 2px solid; pointer-events: none;"></span> 1. </span> I want to circle the number one at any time even if screen gets minimized or zoomed <br><br> <span style="position: relative;"> <span style="position: absolute; top: -5px; left: -8px; height: 25px; width: 25px; border-radius: 50%; border: 2px solid; pointer-events: none;"></span> 2. </span> I want to circle number two too. I styled Card.Body as relative and div as absolute. I manually checked the position of the numbers and I set top and left attributes. <br><br> <span style="position: relative;"> <span style="position: absolute; top: -5px; left: -8px; height: 25px; width: 25px; border-radius: 50%; border: 2px solid; pointer-events: none;"></span> 3. </span> Then I managed to put div using border radius 50% and it is rounded and put on top of numbers but when I zoom it moves from numbers. <br><br> <span style="position: relative;"> <span style="position: absolute; top: -5px; left: -8px; height: 25px; width: 25px; border-radius: 50%; border: 2px solid; pointer-events: none;"></span> 4. </span> please help </p> </div> </body>
代码里加了pointer-events: none是为了避免标记层遮挡下方文本的选中、点击操作,不需要可以删掉。
备选方案(无法修改原文本结构时使用)
如果业务场景不允许修改原文本给目标字符套标签,可以用JS动态计算坐标:
- 先通过DOM Range API选中目标字符,调用
getBoundingClientRect()获取其相对于视口的坐标 - 监听窗口
resize、页面缩放、字体加载完成等事件,每次触发时重新计算坐标,更新标记层的top、left属性即可。
内容的提问来源于stack exchange,提问作者Habtamu
相关产品推荐
相关产品推荐

