[英]Get border around the html DOM element content
我试图捕获像 firefox 检查器这样的 html 元素,所以我在 jquery ( http://jsfiddle.net/fbkxj69b/5/ ) 中编写了几行代码。
但它不适用于某些情况(例如测试 1、5、6、7 和 9)。
有什么建议 ?
谢谢
代码
查询
$(document).ready(function () {
$('.ele').mouseenter(function () {
getCaptured(this);
}).mouseleave(function () {
$('.bline').removeAttr('style');
});
});
function getCaptured(obj){
var pos = obj.getBoundingClientRect();
var txt_lleft = ((pos.width - $(obj).textWidth()) / 2) + pos.left;
var txt_rleft = pos.width - txt_lleft + (pos.left * 2);
var top = pos.top + $(window).scrollTop();
var b = 1;
$('#top').css({ top: Math.max(0, top - b), left: txt_lleft - b, width: $(obj).textWidth() + b, height: b });
$('#bottom').css({ top: top + pos.height, left: txt_lleft - b, width: $(obj).textWidth() + b, height: b });
$('#left').css({ top: top - b, left: Math.max(0, txt_lleft - b), width: b, height: pos.height + b });
$('#right').css({ top: top - b, left: txt_rleft, width: b, height: pos.height + (b * 2) });
}
$.fn.textWidth = function () {
var html_org = $(this).html();
var html_calc = '<span id="ipSpnToGetTxtWdth">' + html_org + '</span>';
$(this).html(html_calc);
var width = $(this).find('span#ipSpnToGetTxtWdth').width();
$(this).html(html_org);
return width;
};
html
<div class="ele">test 1</div>
<span class="ele">test 2</span>
<div style="margin-left: 10px;">
<span class="ele">test 3</span>
</div>
<div style="margin-left: 10px;">
<span style="margin-left: 20px;" class="ele">test 4</span>
</div>
<div style="position: absolute; left: 10px; top: 20px;">
<h4 class="ele">test 5</h4>
</div>
<div style="margin-left: 10px; margin-top: 20px;">
<div style="position: absolute; left: 10px; top: 20px;">
<h4 class="ele">test 6</h4>
</div>
</div>
<h4 class="ele">test 7</h4>
<div style="text-align: center; width: 100%;">
<h4 class="ele">test 8</h4>
</div>
<div style="margin-left: 20px; width: 70%;">
<p class="ele">test 9 test 9 test 9 test 9 test 9 test 9 </p>
</div>
<div class="bline" id="top"></div>
<div class="bline" id="bottom" ></div>
<div class="bline" id="left" ></div>
<div class="bline" id="right" ></div>
css
.bline {
background: #000;
position: absolute;
z-index: 1000000;
}
如果您只想“突出显示”元素的内容(与 chrome 浏览器检查器不同),则可以使用以下逻辑:
jQuery:
$('.ele').hover(function () {
$(this).contents().wrapAll('<span class="highlight"/>');
/*↑↑↑ could bring invalid HTML if wrapping block element inside SPAN */
}, function () {
$(this).find('.highlight').contents().unwrap()
});
CSS:
.highlight {
outline: 1px solid #000;
}
矩形出现在文本之外的可能原因是因为div
被呈现为块元素,但test2
文本不是这种情况,因为它显示在作为inline-block
元素的span
标签inline-block
。
我的建议是将文本test1
的 div 呈现为inline-block
元素或将宽度设置为div
内部文本的大小。
实时代码@Jsfiddle
http://jsfiddle.net/dreamweiver/fbkxj69b/14/
html代码:
<div style= "width:35px;" class="ele">test 1</div> //set to fixed width
<span class="ele">test 2</span>
MDN 链接: https : //developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.