Home >Web Front-end >CSS Tutorial >How Can I Achieve the Functionality of jQuery\'s `.hide()` Without Affecting Element Dimensions?
Finding Alternatives to jQuery's .hide() for Visibility: Hidden
In jQuery, developers have the convenience of using .hide() and .show() to manipulate element visibility by setting the CSS display property to none. However, when the need arises to set element visibility to hidden without changing the element's dimensions, finding an equivalent function like .hide() can pose a challenge.
Custom Plugin Development
One approach is to create a custom jQuery plugin that provides the desired functionality. The following code sample demonstrates the creation of three plugins:
jQuery.fn.visible = function() { return this.css('visibility', 'visible'); }; jQuery.fn.invisible = function() { return this.css('visibility', 'hidden'); }; jQuery.fn.visibilityToggle = function() { return this.css('visibility', function(i, visibility) { return (visibility == 'visible') ? 'hidden' : 'visible'; }); };
With these plugins, you can utilize the extended visible(), invisible(), and visibilityToggle() functions to directly control element visibility without modifying their physical size.
Overloading the Original jQuery toggle() Function
For those who prefer a more familiar approach, it's possible to overload the existing jQuery toggle() function to handle visibility toggling. One method is:
!(function($) { var toggle = $.fn.toggle; $.fn.toggle = function() { var args = $.makeArray(arguments), lastArg = args.pop(); if (lastArg == 'visibility') { return this.visibilityToggle(); } return toggle.apply(this, arguments); }; })(jQuery);
However, this approach is not recommended as it modifies the original toggle() function.
Ultimately, whether you choose to create your own plugin or overload the toggle() function, the provided solutions offer equivalent functionality to jQuery's .hide() for modifying element visibility through the visibility property.
The above is the detailed content of How Can I Achieve the Functionality of jQuery\'s `.hide()` Without Affecting Element Dimensions?. For more information, please follow other related articles on the PHP Chinese website!