基于父w / jQuery调整宽度 [英] Adjust a width based on parent w/ jQuery

查看:96
本文介绍了基于父w / jQuery调整宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够根据父节点的宽度调整类的宽度。当前.myClass具有在CSS中分配的宽度。这样的工作:

I need to be able to adjust a width of a class based on a width of a parent. Currently .myClass has a width assigned in CSS. Would something like this work:

.myClass {
    color: #000;
    width:100px;
}

$(".myClass").width($(".myClass").parent().width());

这将应用于< DIV> ,父项可以是< TD> 或另一个< DIV>

This will be applied to a <DIV> and the parent could be a <TD> or another <DIV>.

推荐答案

你应该工作,但我可能会改为:

What you have should work but I would probably change it to this:

$(".myClass").css("width",$(".myClass").parent().css("width"));

您可以使用 this 第二个 $(。myClass),但您必须测试。

You might be able to use this instead of the second $(".myClass"), but you'd have to test that.

注意它不会改变类本身。它正在改变使用该类的任何元素的宽度。

Keep in mind that it's not changing the class itself. It's changing the width of any element that uses that class.

更新:

如果你要做任何类型的计算与父宽度,那么你应该可能坚持你的原始方法。我喜欢 css 当你按原样应用样式,但这是一个个人喜好。如果你正在对父值进行任何修改,那么 width 可能更好。

If you are going to be doing any sort of calculations with the parent width then you should probably stick with your original method. I like css when you are applying styles "as is" but that is a personal preference. If you are doing any kind of modifications to the parent value then width is probably better.


当元素的宽度需要
时,推荐使用.width()方法
计算。

The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

这篇关于基于父w / jQuery调整宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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