假设我创建了一个这样的HTML元素,

<div id="my-div" class="hidden">Hello, TB3</div>
<div id="my-div" class="hide">Hello, TB4</div>
<div id="my-div" class="d-none">Hello, TB4</div>

如何从jQuery/Javascript显示和隐藏HTML元素。

JavaScript:

$(function(){
  $("#my-div").show();
});

结果:(与任何这些)。

我希望上面的元素被隐藏。

什么是最简单的方法隐藏元素使用Bootstrap和显示它使用jQuery?


当前回答

最近从2.3升级到3.1时遇到了这种情况;我们的jQuery动画(slideDown)崩溃了,因为我们在页面模板的元素上放置了隐藏。我们创建了以名字间隔的Bootstrap类版本,现在它带有丑陋的重要规则。

.rb-hide { display: none; }
.rb-pull-left { float: left; }
etc...

其他回答

最近从2.3升级到3.1时遇到了这种情况;我们的jQuery动画(slideDown)崩溃了,因为我们在页面模板的元素上放置了隐藏。我们创建了以名字间隔的Bootstrap类版本,现在它带有丑陋的重要规则。

.rb-hide { display: none; }
.rb-pull-left { float: left; }
etc...

基于上面的答案,我刚刚添加了我自己的函数,这进一步不与可用的jquery函数如.hide(), .show(), .toggle()冲突。希望能有所帮助。

    /*
     * .hideElement()
     * Hide the matched elements. 
     */
    $.fn.hideElement = function(){
        $(this).addClass('hidden');
        return this;
    };

    /*
     * .showElement()
     * Show the matched elements.
     */
    $.fn.showElement = function(){
        $(this).removeClass('hidden');
        return this;
    };

    /*
     * .toggleElement()
     * Toggle the matched elements.
     */
    $.fn.toggleElement = function(){
        $(this).toggleClass('hidden');
        return this;
    };

简单:

$(function(){
  $("#my-div").removeClass('hide');
});

或者如果你想让这个类仍然在那里:

$(function(){
  $("#my-div").css('display', 'block !important');
});

使用下面的Bootstrap 4代码片段,它扩展了jQuery:

(function( $ ) {

    $.fn.hideShow = function( action ) {

        if ( action.toUpperCase() === "SHOW") {
            // show
            if(this.hasClass("d-none"))
            {
                this.removeClass("d-none");
            }

            this.addClass("d-block");

        }

        if ( action.toUpperCase() === "HIDE" ) {
            // hide
            if(this.hasClass("d-block"))
            {
                this.removeClass("d-block");
            }

            this.addClass("d-none");
      }

          return this;
    };

}( jQuery ));

把上面的代码放到一个文件中。让我们假设"myJqExt.js" 包含jQuery之后再包含该文件。 使用语法使用它 $ () .hideShow(隐藏的); $ () .hideShow(显示);

希望对你们有帮助。: -)

在引导4中,你可以使用d-none类来完全隐藏一个元素。 https://getbootstrap.com/docs/4.0/utilities/display/