javascript - 使用 JQuery 插入 DOM 时 CSS 背景图像无法正确缩放

标签 javascript jquery html css image

背景:

构建内存块 Web 应用程序作为 Web 开发的学习工具。它最初是构建的,现在正在开发响应式设计功能。我希望布局在 6 x 5 板上的各个图 block 能够随着屏幕尺寸的缩小而缩小,将来我计划首先转向移动设备并扩大规模(实践和学习)。

问题:

随着屏幕尺寸的减小,我在保持各个图 block 的 1:1 纵横比时遇到了问题,但在这里找到了该问题的解决方案

Grid of responsive squares

剩下的问题是图 block /卡片/方 block 使用背景图像作为卡片背面的图形表示,然后单击图像即可配对/匹配。当我减小浏览器窗口的大小时,背景图像不会缩放,而是以左上角为原点裁剪掉右侧和底边。我曾多次尝试改变

background-position: center center; 

background-size: cover/contain;

但是裁剪行为没有任何改变。这在 chrome、FF、Opera 网络浏览器中也是如此。经过详尽的搜索后,我没有找到答案。我开始怀疑/推测这可能与这些元素从 JQuery 插入到 DOM 中有关。

作为实验,我添加了 30 个 div 元素 (6 x 5),在 css class="tile"中设置了相同的背景图像,但这次 html 元素被硬编码到 memory.html 中,而不是插入到 DOM 中jQuery。背景图像和正方形/平铺都完美缩放。这似乎表明我的 CSS 是正确的,但不知何故,当从 JQuery 插入到 DOM 中时,这种图像缩放行为不起作用。希望其他人对此有一些见解,因为我已经旋转了一段时间了。我将发布我的代码以供引用

$('document').ready(function(){

    $('#shuffle').click(memory.shuffle);
    $('#deck').change(memory.shuffle);
});

var memory = (function() {

  var arrays = {

          linux: ['assets/img/linux/linuxDebian', 'assets/img/linux/linuxDebian',
              'assets/img/linux/linuxArch', 'assets/img/linux/linuxArch',
              'assets/img/linux/linuxUbuntu', 'assets/img/linux/linuxUbuntu',
              'assets/img/linux/linuxOpenSuse', 'assets/img/linux/linuxOpenSuse',
              'assets/img/linux/linuxNetrunner', 'assets/img/linux/linuxNetrunner',
              'assets/img/linux/linuxSliTaz', 'assets/img/linux/linuxSliTaz',
              'assets/img/linux/linuxAntiX', 'assets/img/linux/linuxAntiX',
              'assets/img/linux/linuxMint', 'assets/img/linux/linuxMint',
              'assets/img/linux/linuxKali', 'assets/img/linux/linuxKali',
              'assets/img/linux/linuxFreeBsd', 'assets/img/linux/linuxFreeBsd',
              'assets/img/linux/linuxGentoo', 'assets/img/linux/linuxGentoo',
              'assets/img/linux/linuxRedHat', 'assets/img/linux/linuxRedHat',
              'assets/img/linux/linuxBodhi', 'assets/img/linux/linuxBodhi',
              'assets/img/linux/linuxCentOS', 'assets/img/linux/linuxCentOS',
              'assets/img/linux/linuxElementary', 'assets/img/linux/linuxElementary'
          ],

          seinfeld: ['assets/img/seinfeld/seinfeldBoss', 'assets/img/seinfeld/seinfeldBoss',
              'assets/img/seinfeld/seinfeldCastanzaMom', 'assets/img/seinfeld/seinfeldCastanzaMom',
              'assets/img/seinfeld/seinfeldCastanza', 'assets/img/seinfeld/seinfeldCastanza',
              'assets/img/seinfeld/seinfeldCosmo', 'assets/img/seinfeld/seinfeldCosmo',
              'assets/img/seinfeld/seinfeldElaine', 'assets/img/seinfeld/seinfeldElaine',
              'assets/img/seinfeld/seinfeldGeorge', 'assets/img/seinfeld/seinfeldGeorge',
              'assets/img/seinfeld/seinfeldGroup', 'assets/img/seinfeld/seinfeldGroup',
              'assets/img/seinfeld/seinfeldJerry', 'assets/img/seinfeld/seinfeldJerry',
              'assets/img/seinfeld/seinfeldNewman', 'assets/img/seinfeld/seinfeldNewman',
              'assets/img/seinfeld/seinfeldNewman2', 'assets/img/seinfeld/seinfeldNewman2',
              'assets/img/seinfeld/seinfeldSoupNazi', 'assets/img/seinfeld/seinfeldSoupNazi',
              'assets/img/seinfeld/seinfeldSteinbrenner', 'assets/img/seinfeld/seinfeldSteinbrenner',
              'assets/img/seinfeld/seinfeldUncleLeo', 'assets/img/seinfeld/seinfeldUncleLeo',
              'assets/img/seinfeld/seinfeldDecider', 'assets/img/seinfeld/seinfeldDecider',
              'assets/img/seinfeld/seinfeldBabu', 'assets/img/seinfeld/seinfeldBabu'
          ],

          starTrek: ['assets/img/starTrek/starTrekWorf', 'assets/img/starTrek/starTrekWorf',
              'assets/img/starTrek/starTrekCisco', 'assets/img/starTrek/starTrekCisco',
              'assets/img/starTrek/starTrekData', 'assets/img/starTrek/starTrekData',
              'assets/img/starTrek/starTrekKirk', 'assets/img/starTrek/starTrekKirk',
              'assets/img/starTrek/starTrekSpock', 'assets/img/starTrek/starTrekSpock',
              'assets/img/starTrek/starTrekQuark', 'assets/img/starTrek/starTrekQuark',
              'assets/img/starTrek/starTrekKira', 'assets/img/starTrek/starTrekKira',
              'assets/img/starTrek/starTrekGarok', 'assets/img/starTrek/starTrekGarok',
              'assets/img/starTrek/starTrekDax', 'assets/img/starTrek/starTrekDax',
              'assets/img/starTrek/starTrekGeordi', 'assets/img/starTrek/starTrekGeordi',
              'assets/img/starTrek/starTrekKhan', 'assets/img/starTrek/starTrekKhan',
              'assets/img/starTrek/starTrekOdo', 'assets/img/starTrek/starTrekOdo',
              'assets/img/starTrek/starTrekBorgQueen', 'assets/img/starTrek/starTrekBorgQueen',
              'assets/img/starTrek/starTrekGalDukat', 'assets/img/starTrek/starTrekGalDukat',
              'assets/img/starTrek/starTrekSevenOfNine', 'assets/img/starTrek/starTrekSevenOfNine'
          ]
      };//end arrays

      /*Global Variables*/
      var card_matched = [];
      var memory_values = [];
      var memory_card_id = [];
      var card_matched = [];
      var card_previous = [];
      var cards_flipped = 0;
      var userAttempt = 0;
      var cards_flipped = 0;
      var gamesPlayed = 0;
      var userSelect = "";
      var deck = "";
      var cardBackGround = "";


      /* Randomly sort an array by calculating a value within array
       * range and then swaps values by randomly calculated value
       */
      Array.prototype.randomizeArray = function() {

              var i = this.length;
              var j = 0;
              var temp = "";

              while (--i > 0) {
                  j = Math.floor(Math.random() * (i + 1));
                  temp = this[j];
                  this[j] = this[i];
                  this[i] = temp;
              } // end while
          } //end randomizeArray

      /* Checks which deck the user has selected to play*/
      function deckSelected() {
        deck = $('#deck option:selected').val();
      } //end deckSelected

      /* Sets the deck background to user selected deck*/
      function changeBackground() {

        switch(deck) {
          case 'linux':
            $('[id^=card_]').css('background', 'url(assets/img/linux/linux_bg.jpg)');
            cardBackGround = 'assets/img/linux/linux_bg.jpg';
            break;

          case 'seinfeld':
            $('[id^=card_]').css('background', 'url(assets/img/seinfeld/seinfeldLogo.jpg)');
            cardBackGround = 'assets/img/seinfeld/seinfeldLogo.jpg';
            break;

          case 'starTrek':
            $('[id^=card_]').css('background', 'url(assets/img/starTrek/starTrekLogo.jpg)');
            cardBackGround = 'assets/img/starTrek/starTrekLogo.jpg';
            break;
        } // End Switch
      } // End changeBackGround

      /*Creates the cards for the memory game after randomizing array selected by user putting each card into its own <div>*/
      function shuffle() {

              var output = '';
              card_previous = [];
              card_matched = [];
              cards_flipped = 0;
              userAttempt = 0;

              //call deckSelected to find which deck to shuffle/create
              deckSelected();

              //shuffle the deck deckSelected returned
              arrays[deck].randomizeArray();

              /*Now that cards are randomized within the array create the cards for the
              game board giving each a unique id and passing (cardId,val) onClick*/
              for (var i = 0; i < arrays[deck].length; i++) {
                  output += '<div class="tile" id="card_' + i + '" onclick="memory.flipCard(this,\'' + arrays[deck][i] + '\')"></div>';
              }

              //put the newly created cards into the gameboard
              document.getElementById('memory-board').innerHTML = output;

              //Change the back of card to represent the deck that is being played
              changeBackground();
          } //End Shuffle

        function flipCard(card, val) {

                //get passed in cards id
                var userSelect = card.id;

                /*check to see if passed in card has been previously matched if so alert user to select different card.*/
                if ($.inArray(userSelect, card_matched) == -1 && $.inArray(userSelect, card_previous) == -1) {

                    if (card.innerHTML == "" && memory_values.length < 2) {

                        card.style.background = 'url(' + val + '.jpg) no-repeat';
                        card.innerHTML = "";

                        /*If this is the first card clicked push card value onto the memory_values(stack)
    		                 *and push card.id onto memory_card_id(stack)*/
                        if (memory_values.length == 0) {
                            memory_values.push(val);
                            memory_card_id.push(card.id);
    			                  card_previous.push(card.id);
                            userAttempt++;
                        } //End if

                        /*if this is the second card clicked push card value onto the memory_values(stack)
    		                 *and push card.id onto memory_card_id(stack)*/
                        else if (memory_values.length == 1) {
                            memory_values.push(val);
                            memory_card_id.push(card.id);
                            userAttempt++;

                            /*Compare card values on the stack after two have been clicked to see if they are the same card.*/
                            if (memory_values[0] == memory_values[1]) {
                                //Value used to later check if all tiles have been flipped
                                cards_flipped += 2;

                                /*Add cards matched to array used to safeguard against user picking cards previously matched*/
                                var temp1 = memory_card_id.pop();
                                var temp2 = memory_card_id.pop();
                                card_matched.push(temp1);
                                card_matched.push(temp2);
                                temp1 = "";
                                temp2 = "";

                                /*Clear out arrays(stack) because cards were a match to get array ready for next user selection*/
                                memory_values = [];
                                memory_card_id = [];

                                /*Check to see if all cards have been flipped if so alert user and generate new board*/
                                if (cards_flipped == arrays[deck].length) {
    				                        //stop timer & calculate attempts call get player score and pass (name, time , attempts)
                                    alert("Congratulations!! This round took " + userAttempt / 2 + " attempts");
                                    document.getElementById('memory-board').innerHTML = "";
                                    shuffle();
                                } //End if
                            } //End if
                            else {
                                //If cards were not a match flip them back over
                                function flipCardBack() {
                                        var card_1 = document.getElementById(memory_card_id[0]);
                                        var card_2 = document.getElementById(memory_card_id[1]);
                                        card_1.style.background = 'url(' + cardBackGround + ') no-repeat';
                                        card_1.innerHTML = "";
                                        card_2.style.background = 'url(' + cardBackGround + ') no-repeat';
                                        card_2.innerHTML = "";
    				                            card_previous = [];
                                        memory_values = [];
                                        memory_card_id = [];
                                    } //End flipCardBack
                                setTimeout(flipCardBack, 700);
                            } //End else
                        } //End else if
                    } //End if
                } //End if
                else {
                    alert("This card has previously been selected, please choose a different tile.");
                } //End else
            } //End flipCard

      var public = {
          shuffle: shuffle,
          flipCard: flipCard,
          arrays: arrays,
          deckSelected: deckSelected,
          changeBackground: changeBackground
      };

      return public;

})();
    /* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

/*
===========================================================
                     Base
===========================================================
*/

    h1 {
  font-size: 45px;
}

h2 {
  font-size: 35px;
}

h3 {
  text-align: center;
  font-size: 20px;
  margin-bottom: 2px;
}

h4 {
  text-align: center;
}

fieldset {
    display: block;
    margin-left: 2px;
    margin-right: 2px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border: 2px groove (internal value);
}

/*
===========================================================
                     Layout
===========================================================
*/

.header-main {
  text-align: center;
  padding: 8px 0 8px 0;
}

.container {
  max-width: 960px;
  padding-top: 10px;
  margin: 0 auto;
  background-color: gray;
}

.col-1-3 {
  float: left;
  width: 33%;
}

#memory-board {
  height: 960px;
  clear: both;
}

.game-controls {
  overflow: auto;
  border-top: 3px black solid;
  border-bottom: 3px black solid;
}

/*
===========================================================
                     Component
===========================================================
*/

.btn {
  height: 52px;
}

.btn-left {
  margin: 5px 0px 5px 4px;
}

.btn-right {
  float: right;
  margin: 5px 0px 0px 5px;
}

.leaderboard {
  margin-top: 2px;
}

.userInput {
  float: left;
  margin: 5px 4px 5px 10px;
}

/*
===========================================================
                     State Rules
===========================================================
*/

.tile {
  float: left;
  position: relative;
  width: 15.666%;
  padding-bottom: 15.666%;
  margin-left: 0.7%;
  margin-top: 0.7%;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
	background-image: url(../img/card_bg.jpg);
	border: 1px solid #000;
	cursor: pointer;
}

/*
===========================================================
                     Responsive
===========================================================
*/
<!DOCTYPE html>
<html lang="en-US">
<head>
  <title>Memory Tile Game</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width", initial-scale="1.0">
  <link rel="stylesheet" type="text/css" href="assets/css/main.css">
  <script rel="text/javascript" src="assets/js/jquery-2.1.4.min.js"></script>
</head>

<body>
  <header class="container header-main">
    <h1>Popular Culture </h1>
    <h2>Memory Tiles Game</h2>
  </header>

  <section class="container game-controls">
    <div class="col-1-3">
        <input type="text" class="userInput" id="playerName" placeholder="Enter Player Name Here">
        <input type="text" class="userInput" id="playerPassword" placeholder="Enter Password Here">
        <button type="button" class="btn btn-left">Login</button>
        <button type="button" class="btn btn-left">Register</button>
    </div>

    <div class="col-1-3 leaderboard">
      <h3>LeaderBoard</h3>
      <h4>1st Place : Dexter Morgan</h4>
      <h4>Linux Distro : 20 Attempts</h4>
    </div>

    <div class="col-1-3">
          <select class="btn btn-right" id="deck" name="decks">
            <option value="Deck To Play">Deck To Play</option>
            <option value="linux">Linux Distro</option>
            <option value="seinfeld">Seinfeld</option>
            <option value="starTrek">Star Trek</option>
          </select>
          <button type="button" class="btn btn-right" id="shuffle">Shuffle Deck</button>
          <button type="button" class="btn btn-right">Leaderboard</button>
    </div>
  </section>

  <section class="container" id="memory-board"></section>

<script src="assets/js/tiles.js"></script>
</body>

</html>

感谢您花时间查看我的帖子。如果我包含了不必要的代码,我深表歉意……这是我的第一篇堆栈溢出帖子。

最佳答案

简写背景属性的设置将覆盖您设置的任何其他背景 CSS,从而有效地删除除图像之外的所有背景样式。

关于javascript - 使用 JQuery 插入 DOM 时 CSS 背景图像无法正确缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33001375/

相关文章:

javascript - 在运行被调用的函数之前触发一个函数运行

jquery - 使用 jQuery 的 Accordion 菜单

c# - 如何使用 JavaScript 或 JQuery 获取 ASP.net 中生成的控件的 ID

jquery - D3 可重复使用的图表功能创建多个图表

javascript - 如何为不同的 Vue 布局使用不同的资源?

javascript - Aurelia 组件未加载 View 模型

javascript - WordPress 自定义元框无法保存

javascript - 在父容器调整大小上重绘谷歌地图

html - CSS 代码未应用于 div?

html - Font Awesome Styling Q(内嵌按钮)