jQuery .css() function not returning expected values

前端 未结 7 1341
情歌与酒
情歌与酒 2020-12-31 08:10

Alright, I\'ve search the jQuery docs (needs somebody devoted to maintaining), I\'ve searched SO, and I\'ve searched Google. I can\'t find the answer to this question.

相关标签:
7条回答
  • 2020-12-31 08:16

    This is not a complete answer to your question but it may be a working solution to caclulate the em values. I adapted this function from here. And here is the updated fiddle.

    $.fn.emWidth = function(){
        var wpx = this.width();
        var temp = $('<div />').css({
            width:'1em', 
            position: 'absolute'
        });
        this.append(temp);
        var oneEm = temp.width();
        temp.remove();
        var value = wpx/oneEm;
        return Math.round(value*100)/100;
    };
    
    0 讨论(0)
  • 2020-12-31 08:17

    In the jQuery manual it is stated:

    The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px).

    Seems like the behaviour of .css() was changed in version 1.3, or at least it seems like that from the bug tracker.

    I was trying to find a good (not hacky) solution also, but I haven't been able yet.

    Also on SO.

    0 讨论(0)
  • 2020-12-31 08:26

    jQuery always* returns dimensions such as width in units of pixels. Perhaps you can borrow the code from this px to em conversion tool to help you get the value you want.

    It looks like 1.4.2 is the most recent version that will still return $(this).css('width') in its assigned unit of measure, but seemingly only if the width is assigned in the style attribute of the element's tag. If it's in a separate CSS declaration like your example, it comes back as pixels still.

    $(this).width() remains to be in pixels.

    (*in versions 1.4.3 and later)

    0 讨论(0)
  • 2020-12-31 08:30

    jQuery now uses a cssHooks feature for certain .css() requests, width and height in particular.

    So the width() function and the .css('width') both run through the same code on occasion.

    0 讨论(0)
  • 2020-12-31 08:31

    if you define the style inline then you can use document.getElementById("myObj").style.width to retrieve the value as it is defined in the inline style

    http://jsfiddle.net/yAnFL/14/

    I'm not sure how to grab the value from an external sheet though.

    0 讨论(0)
  • 2020-12-31 08:33

    As some others have stated, jQuery now uses hooks to intercept evaluation of some css properties. Here is a general solution that lets you get css and bypass those hooks.

    $.fn.hooklessCSS = function(name) {
        var hooks = $.cssHooks;
        $.cssHooks = {};
        var ret = $(this).css(name);
        $.cssHooks = hooks;
        return ret;
    }
    
    0 讨论(0)
提交回复
热议问题