Detecting width: auto in jQuery

为君一笑 提交于 2019-11-30 11:44:37

I don't believe it's possible for the moment. At least not in any other browser than IE. IE implements element.currentStyle which represents styles at they were written in the CSS file. On the other hand, the rest of the browsers implement window.getComputedStyle which returns the computed values of those styles. That's what you receive there, a numeric value instead of auto.

The only way around it would be to parse CSS declarations from document.styleSheets.

References:

This will get either string "auto" or "180px" on absolute values.

$('element').prop('style').width

for width or

$('element').prop('style').height

for height.

Alex

$('#test')[0].style.width=="auto" should work: http://jsfiddle.net/KxTLE/ and http://jsfiddle.net/KxTLE/1/ Try

jQuery.fn.isAuto=function() {
if(this[0]) {
    var ele=$(this[0]);
    if(this[0].style.width=='auto' || ele.outerWidth()==ele.parent().width()) {
        return true;
    } else {
        return false;
    }
}
return undefined;
};

And example: http://jsfiddle.net/KxTLE/6/

As far as I know, there is no native jQuery function to detect auto widths or heights. So I wrote a plugin to do it.

$.fn.isAuto = function(dimension){
    if (dimension == 'width'){
        var originalWidth = this.innerWidth();
        var marginLeft = parseInt(this.css('margin-left'));
        var testMarginWidth = marginLeft+50;
        this.css('margin-left', testMarginWidth);
        var newWidth = this.innerWidth();
        this.css('margin-left', marginLeft);
        if(newWidth<originalWidth){
            return true;    
        }
        else{
            return false;
        }
    }
    else if(dimension == 'height'){
        var originalHeight = this.height();
        this.append('<div id="test"></div>');
        var testHeight = originalHeight+500;
        $('#test').css({height: testHeight});
        var newHeight = this.height();
        $('#test').remove();
        if(newHeight>originalHeight){
            return true;    
        }
        else{
            return false;
        }
    }
};

Originally, I had written it to do height, so I just expanded it to include width. You just call it like this:

$('#element').isAuto('width');

or

$('#element').isAuto('height');

Here is a fiddle demonstrating the plugin's functionality.

I am not quite sure if I am answering your question correctly, but if you use the width() function this will give you an integer representing the rendered width in pixels.

  1. create function
  2. pass css element id to function
  3. write a case where statement to be performed on the width property of the element id

NOTE: to use on mulitple elements would be wise to use a loop with an array of element names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!