如何找到内部元素的宽度 [英] How to find width of inner elements

查看:79
本文介绍了如何找到内部元素的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到其他问题要问同样的事情,尽管这可能与我的搜索短语有关.

I couldn't find any other questions asking the same thing, though that may be a problem with my search phrasing.

我试图弄清楚如何找到具有固定宽度的容器div内包含的所有元素的最大宽度.因此,在下图中,黑框是具有固定宽度的容器div.红色框代表容器div的内容,该内容可能会发生变化.我只想用js中的黑框来找到红色框的宽度.

I'm trying to figure out how to find the largest width of all elements contained inside of a container div with a fixed width. So, in the image below, the black box is the container div with a fixed width. The red box represents the contents of the container div, which are subject to change. I want to find the width of the red box, using only the black box in js.

以下是我一直在努力/尝试的jsfiddle:

Here is a jsfiddle with what I've been working on/trying:

http://jsfiddle.net/w87k5/1/

我尝试过的当前jquery函数,但没有成功:

the current jquery functions I've tried, with no success:

.width();
.innerWidth();
.outerWidth();
.scrollLeft();

注意:我对此容器的内容一无所知.它们可以是任何html元素或html元素的混合,从div到imgs再到iframe.我可以在周围没有固定宽度的情况下放一个红色盒子".黑匣子的溢出将被隐藏.

Note: I do not know ANYTHING about the contents of this container. They could be any html element or mix of html elements, from divs to imgs to iframes. I could put a "red box" without a fixed width surrounding them. Overflow of the black box will be hidden.

更新:容器中可以有任意数量的子代.像这样: http://jsfiddle.net/w87k5/3/

Update: There could be any number of children in the container. Like this: http://jsfiddle.net/w87k5/3/

更新2:我将对所有答案进行基准速度测试,以查看哪个是最快的,然后选择一个.感谢您的所有投入!

Update 2: I'm going to run benchmark speed tests on all of the answers to see which one is the fastest, and select one after that. Thanks for all your input!

基准: 我生成了1000个div,其随机宽度在0到100之间,记录了Date().getTime(),进行了测试,然后再次记录了时间.结果如下:

Benchmarks: I generated 1000 divs with a random width of inbetween 0 and 100, recorded the Date().getTime(), did the test, then recorded time again. Here are the results:

〜2418平均for循环长度的毫秒数.我可能以某种方式弄乱了它吗?

~2418 avg. milliseconds with the for loop for length. I might have messed this one up somehow?

for (var i = 1; i <= count; i++){
        var q = $("#box :nth-child(" + i + ")").width();
        if(q > box){
            box = q;
        }
    }

〜34.4平均.each循环的毫秒数.

~34.4 avg. ms for the .each loop.

〜22.4平均.map函数的ms. (选择答案.)

~22.4 avg. ms for the .map function. (Chosen answer.)

推荐答案

如果需要所有嵌套元素,可以使用*选择器进行搜索,该选择器将返回所有后代元素:

If you need all nested elements can search with * selector which will return all descendent elements:

var widthArray=$('#box *').map(function(){
   return $(this).outerWidth();
}).get();

var maxWIdth= Math.max.apply(Math, widthArray);

仅针对儿童:

var widthArray=$('#box').children().map(function(){....

这篇关于如何找到内部元素的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆