是否可以(使用javascript或jQuery)获取受浮动影响的元素的宽度?当文本由于浮动图像而被推倒时,是否有可能获得其位置和真实宽度?我附上了一张图片,以便更好地解释。
代码示例:
<div>
<img style="...float: left"/>
<h1>A title!</h1>
<p>Text!</p>
<h1>New header added.</h1>
</div>Picture
我需要找到从箭头开始的宽度(灰色框是图像)(虚线是Firefox检查模式的宽度)。
如果可能的话,我想避免更改所有元素的显示类型。谢谢!
发布于 2013-05-15 14:38:14
首先,“全宽”就是真正的宽度。
你可以观看这张图片,它可以帮助你理解为什么firefox会以这种方式告诉你受影响元素的真实宽度和真实位置。
http://i.stack.imgur.com/mB5Ds.png
要获得被浮动图像推到右边的行内文本的宽度,除了使用全宽度减去浮动图像的宽度之外,没有其他好的方法。
var w = $('p').width()
- $('img').width()
- $('img').css('margin-left').replace("px", "")
- $('img').css('margin-right').replace("px", "")
- $('img').css('padding-left').replace("px", "")
- $('img').css('padding-right').replace("px", "")
- $('img').css('border-left-width').replace("px", "")
- $('img').css('border-right-width').replace("px", "");发布于 2014-02-06 14:02:12
我来得有点晚,但我遇到了类似的问题,并提出了一个(到目前为止)似乎在这个问题的所有情况下都有效的解决方案。我喜欢这个解决方案,因为据我所知,它独立于浮动元素工作-你所需要的只是你想要得到的元素的真实宽度/位置,仅此而已。为了提高速度,我用纯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语言,则浮动方向将颠倒
2)输出对象中的所有四个边缘位置都是相对于el.offsetParent的-使用this handy函数可以找到它们相对于文档的位置。
https://stackoverflow.com/questions/16555467
复制相似问题