[英]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.