单击外部主框,使用css退出模式

时间:2018-01-08 11:17:41

标签: jquery html css

我仅使用css创建了这个模态弹出窗口,但是如果我点击" X"我只能离开它。我想添加选项,以便在用户点击主框外部时离开模态,即点击灰色区域。

有关如何做到的任何建议?

是否有必要使用JQuery? 到目前为止,代码非常简单,这就是我试图避免它的原因。

  <div ng-controller="demoCtrl">
    <a href="#openModal">Open Modal</a>
    <div id="openModal" class="modalDialog">
      <div class="content">
        <a href="#close">X</a>
        <h1>Modal Box</h1>
        <button ng-click="changeState()">Show Client</button>
        <div ng-if="client.state">{{client.name}}</div>
      </div>
    </div>
  </div>

Plunker to check the whole thing

谢谢:)

2 个答案:

答案 0 :(得分:2)

您可以在包含所有窗口大小的内容后面添加一个链接,并设置与关闭按钮相同的href

HTML:

  <div ng-controller="demoCtrl">
    <a href="#openModal">Open Modal</a>
    <div id="openModal" class="modalDialog">
      <a class="fullSizeBlock" href="#close">&nbsp;</a>
      <div class="content">
          <a href="#close">X</a>
          <h1>Modal Box</h1>
          <button ng-click="changeState()">Show Client</button>
        <div ng-if="client.state">{{client.name}}</div>
      </div>
    </div>
  </div>

添加了CSS(游标不是必需的,您可以保留默认链接指针):

.fullSizeBlock{
  cursor: initial;
  position: absolute;
  display: block;
  width: 100%;
  height: 100%;
}

答案 1 :(得分:2)

您可以添加另一个a元素作为图层,当您点击它时,它会隐藏模态:

// Code goes here
angular.module("demo", []);

angular
  .module("demo")
  .controller("demoCtrl", ["$scope", function($scope) {
    $scope.client = {
      name: "John Doe",
      state: false
    };
    $scope.changeState = function() {
      $scope.client.state = !$scope.client.state;
    }
  }]);
/* Styles go here */

.modalDialog {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.8);
  z-index: 99;
  opacity: 0;
  -webkit-transition: opacity 400ms ease-in;
  -moz-transition: opacity 400ms ease-in;
  transition: opacity 400ms ease-in;
  pointer-events: none;
}

.modalDialog:target {
  opacity: 1;
  pointer-events: auto;
}


/* CSS of new element */

.close {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}
/*   */
.modalDialog .content {
  width: 400px;
  position: relative;
  margin: 10% auto;
  padding: 15px;
  border-radius: 5px;
  background-color: white;
}
<div ng-controller="demoCtrl">
  <a href="#openModal">Open Modal</a>
  <div id="openModal" class="modalDialog">
    <!-- New element here -->
    <a href="#close" class="close"></a>
    <div class="content">
      <a href="#close">X</a>
      <h1>Modal Box</h1>
      <button ng-click="changeState()">Show Client</button>
      <div ng-if="client.state">{{client.name}}</div>
    </div>
  </div>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>