【问题标题】:Show/Hide div element on button click单击按钮时显示/隐藏 div 元素
【发布时间】:2017-06-20 09:57:36
【问题描述】:

我有以下 div:

<div class="margin-bottom hidden-xs"></div>

这个 div 是隐藏的,当窗口很小时,使用引导类“hidden-xs”,但是当用户点击按钮时我需要显示/隐藏这个 div。 我是网络新手,所以问题是如何通过使用角度、引导程序以正确的方式做到这一点......

【问题讨论】:

  • 贴出你试过的代码。
  • 您不必选择 angular 或 bootstrap。你可以只使用 JavaScript 来做到这一点,而且非常简单
  • 你可以使用jquery。查看click() 事件和toggle() 函数。试一试并展示您的代码,如果您有任何问题,我们可以为您提供帮助。

标签: javascript html css angularjs bootstrap-4


【解决方案1】:

使用 ng-click。在您的 ng 单击中,您可以从变量显示中切换值。指令 ng-show / ng-hide 适用于 css。如果您需要从 DOM 中删除元素,请使用 ng-if 而不是 ng-show

JS

$scope.display = true;
$scope.switch = function(){
    $scope.display =! $scope.display;
}

HTML

<div class="margin-bottom hidden-xs" ng-show="display"></div>

<button class="btn btn-primary btn-xs" ng-click="switch()">Click me !</button>

或者如果您不需要 javascript。

HTML

<div ng-init="display = true">
<div class="margin-bottom hidden-xs" ng-show="display"></div>

    <button class="btn btn-primary btn-xs" ng-click="display =! display">Click me !</button>
</div>

【讨论】:

    【解决方案2】:

    <button onclick="myfunction()">Hide/Show</button>
    
    <div id="myDIV">
    This is my DIV element.
    </div>
    <script>
    function myfunction() {
        var x = document.getElementById('myDIV');
        if (x.style.display === 'none') {
            x.style.display = 'block';
        } else {
            x.style.display = 'none';
        }
    }
    </script>

    【讨论】:

      【解决方案3】:

      要仅使用 javascript 切换显示,您可以试试这个

      https://codepen.io/anon/pen/xrdKEM
      

      function myFunction() {
        var toggle = document.getElementsByClassName('margin-bottom')[0];
        toggle.style.display = toggle.style.display == "none" ? "block" : "none";
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div class="margin-bottom hidden-xs">
        <h1>hello world</h1>
      </div>
      <input type="button" value="hide and show" onclick="myFunction()">

      【讨论】:

        【解决方案4】:

        使用javascript可以轻松完成

        function myFunction() {
            var x = document.getElementById('showHide');
            if (x.style.opacity === '0') {
                x.style.opacity = '1';
            } else {
                x.style.opacity = '0';
            }
        }
        <div id="showHide" class="margin-bottom hidden-xs" onclick="myFunction()">
          This is my DIV element.
        </div>

        【讨论】:

        • 由于 OP 使用的是 AngularJS,这不是最好的解决方案。
        猜你喜欢
        • 2013-01-16
        • 1970-01-01
        • 2016-05-21
        • 1970-01-01
        • 1970-01-01
        • 2021-06-14
        • 2013-04-24
        • 1970-01-01
        • 2017-11-25
        相关资源
        最近更新 更多