代码之家  ›  专栏  ›  技术社区  ›  Elle H

检测宽度:jquery中的auto

  •  15
  • Elle H  · 技术社区  · 14 年前

    我正在使用jquery检索元素的宽度,如果可以指示是否指定了显式的宽度(和高度),我会更喜欢它。

    <div id="test"></div>
    <script type="text/javascript">
    $(function() { alert($('#test').css('width')); });
    </script>
    

    这将根据它在客户机屏幕上占用的像素数提醒DIV的隐式宽度。如果宽度缺失或设置为 width: auto 是否可以使用jquery进行验证?

    也就是说,不是上面的示例返回一个整数,而是返回 auto undefined . 或者,是否存在 isAuto 功能?

    6 回复  |  直到 9 年前
        1
  •  8
  •   Ionuț G. Stan    14 年前

    我认为暂时不可能。至少在IE.IE实现之外的任何其他浏览器中都没有。 element.currentStyle 它表示在CSS文件中写入的样式。另一方面,其他浏览器实现 window.getComputedStyle 它返回 计算值 这些款式。这就是你在那里收到的,一个数值而不是自动的。

    唯一的解决方法是从 document.styleSheets .

    参考文献:

        2
  •  8
  •   prdatur    9 年前

    这将在绝对值上得到字符串“auto”或“180px”。

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

    宽度或

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

    为了身高。

        3
  •  4
  •   Brandon Boone    12 年前

    $('#test')[0].style.width=="auto" 应该工作: http://jsfiddle.net/KxTLE/ http://jsfiddle.net/KxTLE/1/ 尝试

    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;
    };
    

    例如: http://jsfiddle.net/KxTLE/6/

        4
  •  3
  •   zsaat14    11 年前

    据我所知,没有本地jquery函数来检测自动宽度或高度。所以我写了一个插件。

    $.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;
            }
        }
    };
    

    最初,我写它是为了做高度,所以我只是把它扩展到包括宽度。你只是这样称呼它:

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

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

    这里是一个 fiddle 演示插件的功能。

        5
  •  0
  •   Giles Smith    14 年前

    我不太确定我是否正确回答了你的问题,但如果你使用 width() function 这将为您提供一个以像素表示渲染宽度的整数。

        6
  •  0
  •   elitepraetorian    14 年前
    1. 创建函数
    2. 将CSS元素ID传递给函数
    3. 在元素ID的width属性上编写要执行的WHERE语句

    注意:在多个元素上使用具有元素名称数组的循环是明智的。

    推荐文章