是否可以根据开发人员使用 CSS 指定的内容,使用 jQuery 获取元素的宽度(以百分比或像素为单位)?

发布于 2024-09-29 03:29:01 字数 177 浏览 5 评论 0原文

我正在编写一个 jQuery 插件,我需要做的就是确定用户指定的元素的宽度。问题是 .width() 或 .css('width') 将始终报告精确的像素,即使开发人员已经使用 CSS 分配了它,例如 width:90% 。

有没有办法让 jQuery 根据开发人员使用 CSS 指定的内容以 px 或 % 输出元素的宽度?

I'm writing a jQuery plugin and something I need to be able to do is determine the width of an element that the user specifies. The problem is that .width() or .css('width') will always report exact pixels, even if the developer has assigned it e.g. width:90% with CSS.

Is there any way to have jQuery output the width of an element in px or % depending on what the developer has given it with CSS?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

猥琐帝 2024-10-06 03:29:01

我想说最好的方法是自己计算:

var width = $('#someElt').width();
var parentWidth = $('#someElt').offsetParent().width();
var percent = 100*width/parentWidth;

I'd say the best way is to compute it yourself:

var width = $('#someElt').width();
var parentWidth = $('#someElt').offsetParent().width();
var percent = 100*width/parentWidth;
讽刺将军 2024-10-06 03:29:01

这绝对是可能的!

您必须首先 hide() 父元素。这将阻止 JavaScript 计算子元素的像素。

$('.parent').hide();
var width = $('.child').width();
$('.parent').show();
alert(width);

请参阅我的示例

It's most definitely possible!

You must first hide() the parent element. This will prevent JavaScript from calculating pixels for the child element.

$('.parent').hide();
var width = $('.child').width();
$('.parent').show();
alert(width);

See my example.

淡写薰衣草的香 2024-10-06 03:29:01

我认为您可以直接使用样式表('style')对象访问。即便如此,浏览器还是 YMMV。例如elm.style.width

编辑 Peter 的评论::
我不希望“获得%”。根据问题:

<块引用>

我需要能够确定用户指定的元素的宽度...[有没有办法]根据开发人员给出的内容以 px 或 % 为单位输出元素的宽度CSS?

因此,我提供了一种检索“原始”CSS 值的替代方法。这似乎适用于 FF3.6。 YMMV 其他地方(netadictos 的答案可能更便携/通用,我不知道)。再说一次,它并不是要“获得%”

I think you can use stylesheet ('style') object access directly. Even then, YMMV by browser. e.g. elm.style.width.

Edit for Peter's comment::
I am not looking to 'get a %'. As per the question:

I need to be able to do is determine the width of an element that the user specifies ... [is there a way to] output the width of an element in px or % depending on what the developer has given it with CSS?

Thus I provided an alternative to retrieve the "raw" CSS value. This appears to work on FF3.6. YMMV elsewhere (netadictos's answer may be more portable/universal, I do not know). Again, it is not looking to 'get a %'.

救星 2024-10-06 03:29:01

这样做的方法记录在这个 stackoverflow 问题中。

如何使用 JavaScript 读取 CSS 规则值?

您唯一需要知道的是哪个样式表是类或循环所有样式表。以下函数为您提供了该类的所有功能,很容易使用正则表达式来提取您要查找的功能。

function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {

        if(classes[x].selectorText==className) {
                (classes[x].cssText) ? alert(classes[x].cssText) : alert(classes[x].style.cssText);
        }
    }
}
getStyle('.test');

The way to do it is documented in this stackoverflow question.

How do you read CSS rule values with JavaScript?

The only thing you have to know is in which stylesheet is the class or loop through all the stylesheets. The following function gives you all the features of the class, it would be easy to do a regex to extract the feature you look for.

function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {

        if(classes[x].selectorText==className) {
                (classes[x].cssText) ? alert(classes[x].cssText) : alert(classes[x].style.cssText);
        }
    }
}
getStyle('.test');
终止放荡 2024-10-06 03:29:01

出于我的目的,我推断了 MДДГБДLL 的答案。

请记住,我只使用整数百分比。

    var getPercent = function(elem){
        var elemName = elem.attr("id");
        var width = elem.width();
        var parentWidth = elem.offsetParent().width();
        var percent = Math.round(100*width/parentWidth);
        console.log(elemName+"'s width = "+percent+"%");
    }

    getPercent($('#folders'));
    getPercent($('#media'));
    getPercent($('#player'));

For my purposes I extrapolated off MДΓΓ БДLL's answer.

Keep in mind, I'm only working with whole percentages.

    var getPercent = function(elem){
        var elemName = elem.attr("id");
        var width = elem.width();
        var parentWidth = elem.offsetParent().width();
        var percent = Math.round(100*width/parentWidth);
        console.log(elemName+"'s width = "+percent+"%");
    }

    getPercent($('#folders'));
    getPercent($('#media'));
    getPercent($('#player'));
关于从前 2024-10-06 03:29:01

如果您希望将原始元素百分比重新分配为新百分比,最好在 CSS 中定义该值并以某种方式修改元素标识符(类、id 等)以反映新的 CSS 定义。如果新的百分比变量需要可变,则这并不总是适用。

.myClass{
    width:50%;
}

.myNewClass{
    width:35%;
}

通过此(或其他)方法添加删除:

$('.myClass').removeClass('myClass').addClass('myNewClass');

If you are looking to reassign the original elements percentage to a new percentage, it is a good practice to define that value in CSS and modify the elements identifier in some way (class, id, etc) to reflect the new CSS definition. This does not always apply if the new percentage variable needs to be variable.

.myClass{
    width:50%;
}

.myNewClass{
    width:35%;
}

Adding a removing via this (or other) method:

$('.myClass').removeClass('myClass').addClass('myNewClass');
感受沵的脚步 2024-10-06 03:29:01

只是为了使其更加jqueryish

添加这个

$.fn.percWidth = function(){
  return this.outerWidth() / this.parent().outerWidth() * 100;
}

,然后使用

$(selector).percWidth()

这个将返回不带%符号的百分比值,因此您可以在计算中使用它

just to make it more jqueryish

add this

$.fn.percWidth = function(){
  return this.outerWidth() / this.parent().outerWidth() * 100;
}

and then use

$(selector).percWidth()

this will return the percent value without the % sign, so you can use it in calculations

一场春暖 2024-10-06 03:29:01

如果使用样式标签设置,您可以简单地使用 .prop()
例如 $('.selector').prop('style').width.replace('%', '')

If Its set using style tag, You can simply use .prop()
e.g. $('.selector').prop('style').width.replace('%', '')

情丝乱 2024-10-06 03:29:01

为什么没有人“正常”回答这个问题?这里有一些奇怪的方法。

使用 VANILLA JAVASCRIPT

不做:

const a = $(element).width();
const b = $(element).css("width");

做:

const c = $(element)[0].style.width;

Why has nobody answered this 'normally'? There are just those weirdly strange approches here.

USE VANILLA JAVASCRIPT

Don't do:

const a = $(element).width();
const b = $(element).css("width");

Do:

const c = $(element)[0].style.width;
马蹄踏│碎落叶 2024-10-06 03:29:01

我最近也遇到了这个问题,我真的不想做“额外”的工作,即获取父级的宽度并计算百分比。

经过几次快速尝试后,这就是我得到的:

    $($($(table).find('tr')[0]).find('td')).each(function (i, e) {
        var proptW = $(e).prop("style").width;
        console.log(proptW);
    });

所以,我认为这是使用 jQuery 根据开发人员在 css 中指定的内容获取元素宽度值的最接近的方法。

如您所见,我有一个表,我需要检索每列的宽度。

我们无法直接用 jQuery 方法获取开发者指定值(DSV),但与 JavaScript 内置方法结合后,距离获取 DSV 就差一步了。

由于DSV位于Style中,而Style是元素的属性,因此我们可以使用jQuery方法:prop()来获取它。该方法返回样式对象(例如 sty),以便我们可以调用 sty.width 直接获取 DSV。

这不是获取它的纯 jQuery 方法,但它足够简单并且适合我。

I recently met this problem as well, and I really didn't want to do the "extra" work which was getting the width of the parent and calculating the percentage.

After a few quick attempts, this is what I have got:

    $($($(table).find('tr')[0]).find('td')).each(function (i, e) {
        var proptW = $(e).prop("style").width;
        console.log(proptW);
    });

So, I think this is the closest way to use jQuery to get the value of the width of an element based on what the developer specified in the css.

As you can see, I have a table and I need to retrieve the widths for each of columns.

We cannot get the developer specified value(DSV) directly with jQuery method, but after combined with the JavaScript built-in method, it's just one step away from getting the DSV.

As the DSV is in the Style and Style is a property of an element, so we can use the jQuery method: prop() to get it. This method returns the style object(say sty), so that we can call sty.width to get the DSV directly.

This is not the pure jQuery way to get it, but it is simple enough and works for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文