gpt4 book ai didi

Javascript/jQuery 获取 float 受影响元素的真实宽度和位置?

转载 作者:行者123 更新时间:2023-11-28 02:14:43 29 4
gpt4 key购买 nike

是否可以获取受 float 影响的元素的宽度(使用 javascript 或 jQuery)?当文本由于 float 图像而被推倒时,是否可以获得其位置和真实宽度?我附上了一张图片以便更好地解释。

代码示例,

<div>
<img style="...float: left"/>
<h1>A title!</h1>
<p>Text!</p>
<h1>New header added.</h1>
</div>

Picture

我需要找到从箭头开始的宽度,(灰色框是图像)(虚线是根据 Firefox 检查模式的宽度)。

如果可能的话,我想避免更改所有元素的显示类型。谢谢!

最佳答案

我参加聚会有点晚了,但我遇到了类似的问题,并提出了一个解决方案(到目前为止)似乎适用于该问题的所有情况。我喜欢这个解决方案,因为据我所知,它的工作原理独立于 float 元素 - 您所需要的只是您想要获得其真实宽度/位置的元素,仅此而已。出于速度目的,我用纯 Javascript 完成了它,但如果您选择的话,可以使用 jQuery 和单独的 CSS 样式表轻松简化它。

//Get the rendered bounding box for the content of any HTMLElement "el"
var getLimits = function(el) {
//Set a universal style for both tester spans; use "!important" to make sure other styles don't mess things up!
var testerStyle = 'width: 0px!important; overflow: hidden!important; color: transparent!important;';

//Create a 'tester' span and place it BEFORE the content
var testerStart = document.createElement('SPAN');
testerStart.innerHTML = '|';
var testerFloat = ' float: left!important;';
testerStart.setAttribute('style', testerStyle + testerFloat);

//Insert testerStart before the first child of our element
if (el.firstChild) {
el.insertBefore(testerStart, el.firstChild);
} else {
el.appendChild(testerStart);
}

//Create a 'tester' span and place it AFTER the content
var testerEnd = document.createElement('SPAN');
testerEnd.innerHTML = '|';
testerFloat = ' float: right!important;';
testerEnd.setAttribute('style', testerStyle + testerFloat);
el.appendChild(testerEnd);

//Measure the testers
var limits = {
top: testerStart.offsetTop,
bottom: testerEnd.offsetTop + testerEnd.offsetHeight,
left: testerStart.offsetLeft,
right: testerEnd.offsetLeft
}

//Remove the testers and return
el.removeChild(testerStart);
el.removeChild(testerEnd);
return limits;
};

因此,在您的情况下,代码将是:

var paragraphBoundingBox = getLimits($('div>p').get(0));

需要注意的几点:

1) 如果使用RTL语言, float 方向将会相反

2) 输出对象中的所有四个边缘位置都相对于 el.offsetParent - 使用 this handy函数可以找到它们相对于文档的位置。

关于Javascript/jQuery 获取 float 受影响元素的真实宽度和位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16555467/

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