点击图像时如何使用jquery展开div?

时间:2017-07-21 09:40:51

标签: jquery html css

我正在处理图像网格。这是我的HTML代码:

HTML

<div class="container">
  <div *ngFor="let item of items$|async">
    <div class="item">
      <img src="{{item.link}}" height="200px">
    </div>
  </div>
</div>

我想要实现的是每当我点击图片时:div应该像Google图像一样展开。我应该如何使用jquery实现它?

我之前尝试使用纯CSS实现此功能,但之后发生的事情是,当我点击任何图像时,div在每一行都在扩展。它不像谷歌图像那样。如果有人可以帮助我,那将是很棒的。

1 个答案:

答案 0 :(得分:1)

请参阅this

&#13;
&#13;
// You can also use `$` instead of `jQuery` if you are sure that variable is
// not occupied by another library. This `$(callback)` shortcut attaches a
// callback to the DOM load event. It's the same as `$(document).ready(callback)`,
// but shorter. It passed the jQuery object to the callback so we can safely
// use `$` inside of the callback.
jQuery(function($) {
  $('.posts').on('click', '.post-toggle', function() {
    // This is called a delegated event. The handler is attached to
    // the `<ul class="posts">`, so you only need one event handler.
    // But the callback is only executed if `<li class="post">` is in
    // the event chain. It's not only more efficient with memory but
    // also works automagically if posts get added or deleted.

    // `this` is the targetted element, the `post-toggle`. It's a normal
    // DOM element object so we convert it to a jQuery object with
    // `$(this)`.

    // `closest('.post')` finds the closest ancestor with class `post`.

    // `find('.post-content')` finds the closes descendant with class `post-content`.

    // `toggle()` toggles visibility using the `display` property.
    $(this).closest('.post').find('.post-content').toggle();
  });
});
&#13;
ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.clearfix:after {
  content: '';
  clear: both;
  display: table;
}

.post {
  margin: 0 0 1.5em;
}

.post-toggle {
  float: left;
  width: 4em;
  height: 4em;
  background: #bada55;
}

.post-content {
  display: none;
  height: 8em;
  border: 0.25em solid #bada55;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="posts">
  <li class="post clearfix">
    <div class="post-toggle"></div>
    <div class="post-content"></div>
  </li>
  <li class="post clearfix">
    <div class="post-toggle"></div>
    <div class="post-content"></div>
  </li>
  <li class="post clearfix">
    <div class="post-toggle"></div>
    <div class="post-content"></div>
  </li>
</ul>
&#13;
&#13;
&#13;