gpt4 book ai didi

javascript - 获取 html DOM 元素内容周围的边框

转载 作者:行者123 更新时间:2023-12-02 16:05:24 25 4
gpt4 key购买 nike

我试图像firefox检查器一样捕获html元素,所以我在jquery中编写了几行代码(http://jsfiddle.net/fbkxj69b/5/)。

但它不适用于某些情况(例如测试 1、5、6、7 和 9)。

有什么建议吗?

谢谢

代码

jquery

$(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;
}

-jsFiddle-

关于javascript - 获取 html DOM 元素内容周围的边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30803070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com