首页 > 解决方案 > 如何使用 javascript 在 html 文件中动态绘制矩形?谷歌浏览器扩展页面标尺具有类似的功能

问题描述

我想在 HTML 文件中的文本或段落上绘制矩形。我想在不使用画布的情况下使用 javascript 来实现这一点。也可以存在多个矩形来选择多个段落。是否有任何库可以实现这种功能。

单击此处查看预期结果

页面标尺链接在这里https://chrome.google.com/webstore/detail/page-ruler-redux/giejhjebcalaheckengmchjekofhhmal?hl=en-US

标签: javascriptshapes

解决方案


如果要突出显示纯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>


推荐阅读