javascript - 如何将图像放置在每个单独的网格正方形中?

标签 javascript html css

我找到了一个正方形网格,但我想在每个正方形中放置不同的图像,无论该图像是链接还是文件。我应该如何为我的网格设置 HTML 以允许每个网格都有图像?另外,我也想保持网格内图像的响应能力。

如果有人可以通过示例进行解释,那就太好了。

预先感谢您的所有帮助!

网格代码以及代码片段如下所示:

/*! modernizr 3.5.0 (Custom Build) | MIT *
 * https://modernizr.com/download/?-cssgrid_cssgridlegacy-setclasses !*/
! function(e, n, t) {
  function r(e, n) {
    return typeof e === n
  }

  function o() {
    var e, n, t, o, s, i, l;
    for (var a in w)
      if (w.hasOwnProperty(a)) {
        if (e = [], n = w[a], n.name && (e.push(n.name.toLowerCase()), n.options && n.options.aliases && n.options.aliases.length))
          for (t = 0; t < n.options.aliases.length; t++) e.push(n.options.aliases[t].toLowerCase());
        for (o = r(n.fn, "function") ? n.fn() : n.fn, s = 0; s < e.length; s++) i = e[s], l = i.split("."), 1 === l.length ? Modernizr[l[0]] = o : (!Modernizr[l[0]] || Modernizr[l[0]] instanceof Boolean || (Modernizr[l[0]] = new Boolean(Modernizr[l[0]])), Modernizr[l[0]][l[1]] = o), C.push((o ? "" : "no-") + l.join("-"))
      }
  }

  function s(e) {
    var n = _.className,
      t = Modernizr._config.classPrefix || "";
    if (x && (n = n.baseVal), Modernizr._config.enableJSClass) {
      var r = new RegExp("(^|\\s)" + t + "no-js(\\s|$)");
      n = n.replace(r, "$1" + t + "js$2")
    }
    Modernizr._config.enableClasses && (n += " " + t + e.join(" " + t), x ? _.className.baseVal = n : _.className = n)
  }

  function i(e, n) {
    return !!~("" + e).indexOf(n)
  }

  function l(e) {
    return e.replace(/([a-z])-([a-z])/g, function(e, n, t) {
      return n + t.toUpperCase()
    }).replace(/^-/, "")
  }

  function a() {
    return "function" != typeof n.createElement ? n.createElement(arguments[0]) : x ? n.createElementNS.call(n, "http://www.w3.org/2000/svg", arguments[0]) : n.createElement.apply(n, arguments)
  }

  function u(e, n) {
    return function() {
      return e.apply(n, arguments)
    }
  }

  function f(e, n, t) {
    var o;
    for (var s in e)
      if (e[s] in n) return t === !1 ? e[s] : (o = n[e[s]], r(o, "function") ? u(o, t || n) : o);
    return !1
  }

  function c(e) {
    return e.replace(/([A-Z])/g, function(e, n) {
      return "-" + n.toLowerCase()
    }).replace(/^ms-/, "-ms-")
  }

  function d(n, t, r) {
    var o;
    if ("getComputedStyle" in e) {
      o = getComputedStyle.call(e, n, t);
      var s = e.console;
      if (null !== o) r && (o = o.getPropertyValue(r));
      else if (s) {
        var i = s.error ? "error" : "log";
        s[i].call(s, "getComputedStyle returning null, its possible modernizr test results are inaccurate")
      }
    } else o = !t && n.currentStyle && n.currentStyle[r];
    return o
  }

  function p() {
    var e = n.body;
    return e || (e = a(x ? "svg" : "body"), e.fake = !0), e
  }

  function m(e, t, r, o) {
    var s, i, l, u, f = "modernizr",
      c = a("div"),
      d = p();
    if (parseInt(r, 10))
      for (; r--;) l = a("div"), l.id = o ? o[r] : f + (r + 1), c.appendChild(l);
    return s = a("style"), s.type = "text/css", s.id = "s" + f, (d.fake ? d : c).appendChild(s), d.appendChild(c), s.styleSheet ? s.styleSheet.cssText = e : s.appendChild(n.createTextNode(e)), c.id = f, d.fake && (d.style.background = "", d.style.overflow = "hidden", u = _.style.overflow, _.style.overflow = "hidden", _.appendChild(d)), i = t(c, e), d.fake ? (d.parentNode.removeChild(d), _.style.overflow = u, _.offsetHeight) : c.parentNode.removeChild(c), !!i
  }

  function g(n, r) {
    var o = n.length;
    if ("CSS" in e && "supports" in e.CSS) {
      for (; o--;)
        if (e.CSS.supports(c(n[o]), r)) return !0;
      return !1
    }
    if ("CSSSupportsRule" in e) {
      for (var s = []; o--;) s.push("(" + c(n[o]) + ":" + r + ")");
      return s = s.join(" or "), m("@supports (" + s + ") { #modernizr { position: absolute; } }", function(e) {
        return "absolute" == d(e, null, "position")
      })
    }
    return t
  }

  function y(e, n, o, s) {
    function u() {
      c && (delete N.style, delete N.modElem)
    }
    if (s = r(s, "undefined") ? !1 : s, !r(o, "undefined")) {
      var f = g(e, o);
      if (!r(f, "undefined")) return f
    }
    for (var c, d, p, m, y, v = ["modernizr", "tspan", "samp"]; !N.style && v.length;) c = !0, N.modElem = a(v.shift()), N.style = N.modElem.style;
    for (p = e.length, d = 0; p > d; d++)
      if (m = e[d], y = N.style[m], i(m, "-") && (m = l(m)), N.style[m] !== t) {
        if (s || r(o, "undefined")) return u(), "pfx" == n ? m : !0;
        try {
          N.style[m] = o
        } catch (h) {}
        if (N.style[m] != y) return u(), "pfx" == n ? m : !0
      }
    return u(), !1
  }

  function v(e, n, t, o, s) {
    var i = e.charAt(0).toUpperCase() + e.slice(1),
      l = (e + " " + P.join(i + " ") + i).split(" ");
    return r(n, "string") || r(n, "undefined") ? y(l, n, o, s) : (l = (e + " " + z.join(i + " ") + i).split(" "), f(l, n, t))
  }

  function h(e, n, r) {
    return v(e, t, t, n, r)
  }
  var C = [],
    w = [],
    S = {
      _version: "3.5.0",
      _config: {
        classPrefix: "",
        enableClasses: !0,
        enableJSClass: !0,
        usePrefixes: !0
      },
      _q: [],
      on: function(e, n) {
        var t = this;
        setTimeout(function() {
          n(t[e])
        }, 0)
      },
      addTest: function(e, n, t) {
        w.push({
          name: e,
          fn: n,
          options: t
        })
      },
      addAsyncTest: function(e) {
        w.push({
          name: null,
          fn: e
        })
      }
    },
    Modernizr = function() {};
  Modernizr.prototype = S, Modernizr = new Modernizr;
  var _ = n.documentElement,
    x = "svg" === _.nodeName.toLowerCase(),
    b = "Moz O ms Webkit",
    P = S._config.usePrefixes ? b.split(" ") : [];
  S._cssomPrefixes = P;
  var z = S._config.usePrefixes ? b.toLowerCase().split(" ") : [];
  S._domPrefixes = z;
  var E = {
    elem: a("modernizr")
  };
  Modernizr._q.push(function() {
    delete E.elem
  });
  var N = {
    style: E.elem.style
  };
  Modernizr._q.unshift(function() {
    delete N.style
  }), S.testAllProps = v, S.testAllProps = h, Modernizr.addTest("cssgridlegacy", h("grid-columns", "10px", !0)), Modernizr.addTest("cssgrid", h("grid-template-rows", "none", !0)), o(), s(C), delete S.addTest, delete S.addAsyncTest;
  for (var T = 0; T < Modernizr._q.length; T++) Modernizr._q[T]();
  e.Modernizr = Modernizr
}(window, document);
.grid {
  max-width: 300px;
  margin: 0 auto;
}

.item {
  position: relative;
  display: block;
  margin-bottom: 1vw;
  background: #ccc;
}

.item:hover {
  color: black;
}

.item:after {
  content: ' ';
  display: block;
  width: 100%;
  padding-bottom: 100%;
  background: #aaa;
}

.item__inner {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  font-size: 24px;
  color: white;
}

@media (min-width: 600px) {
  .grid {
    max-width: 1200px;
  }
  @supports (display: grid) {
    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-column-gap: 1vw;
      grid-row-gap: 1vw;
    }
  }
}

@media (min-width: 600px) and (max-width: 999px) {
  .no-cssgrid .item {
    float: left;
    width: calc(100%/3 - 10px);
    margin-right: 10px;
  }
  .no-cssgrid .item:nth-child(3n) {
    margin-right: 0;
  }
  @supports (display: grid) {
    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-column-gap: 1vw;
      grid-row-gap: 1vw;
    }
    .item {
      margin-bottom: 0;
    }
    .item:nth-child(1) {
      grid-column-end: span 2;
    }
    .item:nth-child(1):after {
      display: none;
    }
    .item:nth-child(3) {
      grid-row-end: span 2;
    }
    .item:nth-child(6) {
      grid-column-end: span 2;
    }
    .item:nth-child(6):after {
      padding-bottom: 50%;
    }
  }
}

@media (min-width: 1000px) {
  .no-cssgrid .item {
    float: left;
    width: calc(100%/4 - 10px);
    margin-right: 10px;
  }
  .no-cssgrid .item:nth-child(4n) {
    margin-right: 0;
  }
  @supports (display: grid) {
    .grid {
      grid-template-columns: 1fr 1fr 1fr 1fr;
    }
    .item {
      margin-bottom: 0;
    }
    .item:nth-child(1) {
      grid-column-end: span 2;
      grid-row-end: span 2;
    }
  }
}
<div class="grid">
  <div class="item">
    <div class="item__inner">Item</div>
  </div>
  <a href="#" class="item">
    <div class="item__inner">Item</div>
  </a>
  <a href="#" class="item">
    <div class="item__inner">Item</div>
  </a>
  <a href="#" class="item">
    <div class="item__inner">Item</div>
  </a>
  <a href="#" class="item">
    <div class="item__inner">Item</div>
  </a>
  <a href="#" class="item">
    <div class="item__inner">Item</div>
  </a>
  <a href="#" class="item">
    <div class="item__inner">Item</div>
  </a>
  <a href="#" class="item">
    <div class="item__inner">Item</div>
  </a>
  <a href="#" class="item">
    <div class="item__inner">Item</div>
  </a>
</div>

最佳答案

希望对您有所帮助。谢谢。

/*! modernizr 3.5.0 (Custom Build) | MIT *
 * https://modernizr.com/download/?-cssgrid_cssgridlegacy-setclasses !*/
! function(e, n, t) {
  function r(e, n) {
    return typeof e === n
  }

  function o() {
    var e, n, t, o, s, i, l;
    for (var a in w)
      if (w.hasOwnProperty(a)) {
        if (e = [], n = w[a], n.name && (e.push(n.name.toLowerCase()), n.options && n.options.aliases && n.options.aliases.length))
          for (t = 0; t < n.options.aliases.length; t++) e.push(n.options.aliases[t].toLowerCase());
        for (o = r(n.fn, "function") ? n.fn() : n.fn, s = 0; s < e.length; s++) i = e[s], l = i.split("."), 1 === l.length ? Modernizr[l[0]] = o : (!Modernizr[l[0]] || Modernizr[l[0]] instanceof Boolean || (Modernizr[l[0]] = new Boolean(Modernizr[l[0]])), Modernizr[l[0]][l[1]] = o), C.push((o ? "" : "no-") + l.join("-"))
      }
  }

  function s(e) {
    var n = _.className,
      t = Modernizr._config.classPrefix || "";
    if (x && (n = n.baseVal), Modernizr._config.enableJSClass) {
      var r = new RegExp("(^|\\s)" + t + "no-js(\\s|$)");
      n = n.replace(r, "$1" + t + "js$2")
    }
    Modernizr._config.enableClasses && (n += " " + t + e.join(" " + t), x ? _.className.baseVal = n : _.className = n)
  }

  function i(e, n) {
    return !!~("" + e).indexOf(n)
  }

  function l(e) {
    return e.replace(/([a-z])-([a-z])/g, function(e, n, t) {
      return n + t.toUpperCase()
    }).replace(/^-/, "")
  }

  function a() {
    return "function" != typeof n.createElement ? n.createElement(arguments[0]) : x ? n.createElementNS.call(n, "http://www.w3.org/2000/svg", arguments[0]) : n.createElement.apply(n, arguments)
  }

  function u(e, n) {
    return function() {
      return e.apply(n, arguments)
    }
  }

  function f(e, n, t) {
    var o;
    for (var s in e)
      if (e[s] in n) return t === !1 ? e[s] : (o = n[e[s]], r(o, "function") ? u(o, t || n) : o);
    return !1
  }

  function c(e) {
    return e.replace(/([A-Z])/g, function(e, n) {
      return "-" + n.toLowerCase()
    }).replace(/^ms-/, "-ms-")
  }

  function d(n, t, r) {
    var o;
    if ("getComputedStyle" in e) {
      o = getComputedStyle.call(e, n, t);
      var s = e.console;
      if (null !== o) r && (o = o.getPropertyValue(r));
      else if (s) {
        var i = s.error ? "error" : "log";
        s[i].call(s, "getComputedStyle returning null, its possible modernizr test results are inaccurate")
      }
    } else o = !t && n.currentStyle && n.currentStyle[r];
    return o
  }

  function p() {
    var e = n.body;
    return e || (e = a(x ? "svg" : "body"), e.fake = !0), e
  }

  function m(e, t, r, o) {
    var s, i, l, u, f = "modernizr",
      c = a("div"),
      d = p();
    if (parseInt(r, 10))
      for (; r--;) l = a("div"), l.id = o ? o[r] : f + (r + 1), c.appendChild(l);
    return s = a("style"), s.type = "text/css", s.id = "s" + f, (d.fake ? d : c).appendChild(s), d.appendChild(c), s.styleSheet ? s.styleSheet.cssText = e : s.appendChild(n.createTextNode(e)), c.id = f, d.fake && (d.style.background = "", d.style.overflow = "hidden", u = _.style.overflow, _.style.overflow = "hidden", _.appendChild(d)), i = t(c, e), d.fake ? (d.parentNode.removeChild(d), _.style.overflow = u, _.offsetHeight) : c.parentNode.removeChild(c), !!i
  }

  function g(n, r) {
    var o = n.length;
    if ("CSS" in e && "supports" in e.CSS) {
      for (; o--;)
        if (e.CSS.supports(c(n[o]), r)) return !0;
      return !1
    }
    if ("CSSSupportsRule" in e) {
      for (var s = []; o--;) s.push("(" + c(n[o]) + ":" + r + ")");
      return s = s.join(" or "), m("@supports (" + s + ") { #modernizr { position: absolute; } }", function(e) {
        return "absolute" == d(e, null, "position")
      })
    }
    return t
  }

  function y(e, n, o, s) {
    function u() {
      c && (delete N.style, delete N.modElem)
    }
    if (s = r(s, "undefined") ? !1 : s, !r(o, "undefined")) {
      var f = g(e, o);
      if (!r(f, "undefined")) return f
    }
    for (var c, d, p, m, y, v = ["modernizr", "tspan", "samp"]; !N.style && v.length;) c = !0, N.modElem = a(v.shift()), N.style = N.modElem.style;
    for (p = e.length, d = 0; p > d; d++)
      if (m = e[d], y = N.style[m], i(m, "-") && (m = l(m)), N.style[m] !== t) {
        if (s || r(o, "undefined")) return u(), "pfx" == n ? m : !0;
        try {
          N.style[m] = o
        } catch (h) {}
        if (N.style[m] != y) return u(), "pfx" == n ? m : !0
      }
    return u(), !1
  }

  function v(e, n, t, o, s) {
    var i = e.charAt(0).toUpperCase() + e.slice(1),
      l = (e + " " + P.join(i + " ") + i).split(" ");
    return r(n, "string") || r(n, "undefined") ? y(l, n, o, s) : (l = (e + " " + z.join(i + " ") + i).split(" "), f(l, n, t))
  }

  function h(e, n, r) {
    return v(e, t, t, n, r)
  }
  var C = [],
    w = [],
    S = {
      _version: "3.5.0",
      _config: {
        classPrefix: "",
        enableClasses: !0,
        enableJSClass: !0,
        usePrefixes: !0
      },
      _q: [],
      on: function(e, n) {
        var t = this;
        setTimeout(function() {
          n(t[e])
        }, 0)
      },
      addTest: function(e, n, t) {
        w.push({
          name: e,
          fn: n,
          options: t
        })
      },
      addAsyncTest: function(e) {
        w.push({
          name: null,
          fn: e
        })
      }
    },
    Modernizr = function() {};
  Modernizr.prototype = S, Modernizr = new Modernizr;
  var _ = n.documentElement,
    x = "svg" === _.nodeName.toLowerCase(),
    b = "Moz O ms Webkit",
    P = S._config.usePrefixes ? b.split(" ") : [];
  S._cssomPrefixes = P;
  var z = S._config.usePrefixes ? b.toLowerCase().split(" ") : [];
  S._domPrefixes = z;
  var E = {
    elem: a("modernizr")
  };
  Modernizr._q.push(function() {
    delete E.elem
  });
  var N = {
    style: E.elem.style
  };
  Modernizr._q.unshift(function() {
    delete N.style
  }), S.testAllProps = v, S.testAllProps = h, Modernizr.addTest("cssgridlegacy", h("grid-columns", "10px", !0)), Modernizr.addTest("cssgrid", h("grid-template-rows", "none", !0)), o(), s(C), delete S.addTest, delete S.addAsyncTest;
  for (var T = 0; T < Modernizr._q.length; T++) Modernizr._q[T]();
  e.Modernizr = Modernizr
}(window, document);
.grid {
  max-width: 300px;
  margin: 0 auto;
}

.item {
  position: relative;
  display: block;
  margin-bottom: 1vw;
  background: #ccc;
}

.item:hover {
  color: black;
}

.item:after {
  content: ' ';
  display: block;
  width: 100%;
  padding-bottom: 100%;
  background: #aaa;
}

.item__inner {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  font-size: 24px;
  color: white;
}

@media (min-width: 600px) {
  .grid {
    max-width: 1200px;
  }
  @supports (display: grid) {
    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-column-gap: 1vw;
      grid-row-gap: 1vw;
    }
  }
}

@media (min-width: 600px) and (max-width: 999px) {
  .no-cssgrid .item {
    float: left;
    width: calc(100%/3 - 10px);
    margin-right: 10px;
  }
  .no-cssgrid .item:nth-child(3n) {
    margin-right: 0;
  }
  @supports (display: grid) {
    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-column-gap: 1vw;
      grid-row-gap: 1vw;
    }
    .item {
      margin-bottom: 0;
    }
    .item:nth-child(1) {
      grid-column-end: span 2;
    }
    .item:nth-child(1):after {
      display: none;
    }
    .item:nth-child(3) {
      grid-row-end: span 2;
    }
    .item:nth-child(6) {
      grid-column-end: span 2;
    }
    .item:nth-child(6):after {
      padding-bottom: 50%;
    }
  }
}

@media (min-width: 1000px) {
  .no-cssgrid .item {
    float: left;
    width: calc(100%/4 - 10px);
    margin-right: 10px;
  }
  .no-cssgrid .item:nth-child(4n) {
    margin-right: 0;
  }
  @supports (display: grid) {
    .grid {
      grid-template-columns: 1fr 1fr 1fr 1fr;
    }
    .item {
      margin-bottom: 0;
    }
    .item:nth-child(1) {
      grid-column-end: span 2;
      grid-row-end: span 2;
    }
  }
}
<div class="grid">
  <div class="item">
   <img class="item__inner" src="http://files.all-free-download.com//downloadfiles/wallpapers/1920_1200/elephant_wallpaper_elephants_animals_325.jpg">
  </div>
  <a href="#" class="item">
 <img class="item__inner" src="http://files.all-free-download.com//downloadfiles/wallpapers/1920_1200/elephant_wallpaper_elephants_animals_325.jpg">      </a>
  <a href="#" class="item">
 <img class="item__inner" src="http://files.all-free-download.com//downloadfiles/wallpapers/1920_1200/elephant_wallpaper_elephants_animals_325.jpg">      </a>
  <a href="#" class="item">
 <img class="item__inner" src="http://files.all-free-download.com//downloadfiles/wallpapers/1920_1200/elephant_wallpaper_elephants_animals_325.jpg">      </a>
  <a href="#" class="item">
 <img class="item__inner" src="http://files.all-free-download.com//downloadfiles/wallpapers/1920_1200/elephant_wallpaper_elephants_animals_325.jpg">      </a>
  <a href="#" class="item">
 <img class="item__inner" src="http://files.all-free-download.com//downloadfiles/wallpapers/1920_1200/elephant_wallpaper_elephants_animals_325.jpg">      </a>
  <a href="#" class="item">
 <img class="item__inner" src="http://files.all-free-download.com//downloadfiles/wallpapers/1920_1200/elephant_wallpaper_elephants_animals_325.jpg">      </a>
  <a href="#" class="item">
 <img class="item__inner" src="http://files.all-free-download.com//downloadfiles/wallpapers/1920_1200/elephant_wallpaper_elephants_animals_325.jpg">      </a>
  <a href="#" class="item">
 <img class="item__inner" src="http://files.all-free-download.com//downloadfiles/wallpapers/1920_1200/elephant_wallpaper_elephants_animals_325.jpg">      </a>
</div>

关于javascript - 如何将图像放置在每个单独的网格正方形中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49548148/

相关文章:

javascript - WordPress:在javascript中获取页面语言

javascript - 在 Chart.js 中对一个数据集中的各个点进行样式设置

javascript - 如何更新画笔上多线的标记?

html - 使用 span 创建分隔符

javascript - 具有自动加载功能的 html5 播放器无法正常工作

jquery - 放置 Nivo-Slider 加载屏幕

javascript - 从字符串中找到最接近 0 的数字?

jquery - 在 CSS 中,不透明度 :0 and display:none? 之间有什么区别

.net - 在 Orchard 中包含 css 文件

javascript - javascript 一次调用多个变量