jQuery min-width vs width:如何删除px?

Dan*_*Dan 8 javascript css jquery width

在这里尝试一些基本的jQuery和JavaScript.

.width()给我一个整数值.该.css('min-width')给我一个值的结局px.因此我不能按原样做数学.推荐的工作是什么?

alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));

if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*ill 21

用途replace():

alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').replace('px', ''));
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用以下parseInt功能:

alert(parseInt('1px')); //Result: 1
Run Code Online (Sandbox Code Playgroud)


Ale*_*ich 9

更好的方法是使用parseInt.jQuery的功能.width().height()工作非常有用.

此外,最好将这些值的获取封装在独立函数中:

  • .minHeight(),.minHeight( size ),.minHeight( function() )
  • .maxHeight(), ...
  • .minWidth(), ...
  • .maxWidth(), ...

像这样:

(function($, undefined) {

    var oldPlugins = {};

    $.each([ "min", "max" ], function(_, name) {

        $.each([ "Width", "Height" ], function(_, dimension) {

            var type = name + dimension,
                cssProperty = [name, dimension.toLowerCase()].join('-');

            oldPlugins[ type ] = $.fn[ type ];

            $.fn[ type ] = function(size) {
                var elem = this[0];
                if (!elem) {
                    return !size ? null : this;
                }

                if ($.isFunction(size)) {
                    return this.each(function(i) {
                        var $self = $(this);
                        $self[ type ](size.call(this, i, $self[ type ]()));
                    });
                }

                if (size === undefined) {
                    var orig = $.css(elem, cssProperty),
                        ret = parseFloat(orig);

                    return jQuery.isNaN(ret) ? orig : ret;
                } else {
                    return this.css(cssProperty, typeof size === "string" ? size : size + "px");
                }
            };

        });

    });

})(jQuery);
Run Code Online (Sandbox Code Playgroud)

您的代码将转向:

alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth()) {
Run Code Online (Sandbox Code Playgroud)