javascript - 如何使用 javascript 在 html 文件中动态绘制矩形?谷歌浏览器扩展页面标尺具有类似的功能
问题描述
我想在 HTML 文件中的文本或段落上绘制矩形。我想在不使用画布的情况下使用 javascript 来实现这一点。也可以存在多个矩形来选择多个段落。是否有任何库可以实现这种功能。
页面标尺链接在这里https://chrome.google.com/webstore/detail/page-ruler-redux/giejhjebcalaheckengmchjekofhhmal?hl=en-US
解决方案
如果要突出显示纯p
元素,可以操作段落的 backgroundColor 属性,但必须确保它们已显示inline-block
。
document.getElementById('bttn').addEventListener('click', highlight);
function highlight() {
var p = document.getElementById('target');
p.style.backgroundColor = '#ff0000'; //change background color
}
<!--make sure the paragraph is displayed inline-block, or else the entire line will be highlighted. -->
<p id="target" style="display:inline-block">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button id="bttn">Click here to highlight</button>