Я хочу, чтобы изображение менялось в зависимости от того, где я выбрал go - PullRequest
1 голос
/ 03 апреля 2020

Итак, я делаю эту текстовую приключенческую игру, и в основном вы можете ввести набор действий, где вы бы хотели go на этой воображаемой карте. Например, введите в поле ввода «север», и в результате вы получите «вы решили go на север и встретили вас в супермаркете». Что я хотел бы знать, если бы было возможно, если бы я мог добавить изображение в зависимости от выбранного места назначения? Как и в примере выше, я выбрал север и оказался в супермаркете, поэтому результатом будет изображение супермаркета. Я уже разобрался с работой операторов if, отображающих текст, чтобы дать игроку знать, куда он пошел, но я также хотел бы знать, как добавить изображение вместе с ним?

...

<p> Pick a direction to go </p>

<input id = "input" type = "text" placeholder = "Type Help for actions"/><button onClick = "button()">Confirm</button>
<p id = "message"></p>


<script>

  function button() {
    var textInput;
    var newInput = input.value;
    if (newInput == "North") {
      textInput = "you went to the Abandoned Church";
      document.getElementById("message").innerHTML = textInput;
    }

    if (newInput == "North Again") {
      textInput = "you went to the Abandoned Someplace";
      document.getElementById("message").innerHTML = textInput;
    }

    if (newInput == "Help") {
      textInput = "Commands you can use: <ul><li>South</li><li>North</li><li>East</li><li>West</li><li>North Again</li><li>South again</li><li>West Again</li><li>East Again</li><li>North One More</li><li>East Once More</li><li>West Once More</li><li>South Once More</li>";
      document.getElementById("message").innerHTML = textInput;
    }


  }

</script>

Ответы [ 3 ]

0 голосов
/ 03 апреля 2020

Да, вы можете сделать это двумя способами.

Решение A - комбинация HTML / JS:

<!DOCTYPE html>
<html>
<body>

<img id="myImg"/>

<p>Click the button to change the value of the src attribute of the image.</p>
<p><b>Note:</b> The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.</p>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("myImg").src = "hackanm.gif";
}
</script>

</body>
</html>

В этом подходе у вас есть предопределенное изображение в вашем теге html, но у него нет img sr c. Вы можете установить это в нужное время в вашем javascript - идеально, когда они выбирают направление или опцию.

Так что в вашем случае это будет выглядеть так:

<p> Pick a direction to go </p>

<img id="myImg"/>

<input id = "input" type = "text" placeholder = "Type Help for actions"/><button onClick = "button()">Confirm</button>
<p id = "message"></p>


<script>

  function button() {
    var textInput;
    var newInput = input.value;
    if (newInput == "North") {
      textInput = "you went to the Abandoned Church";
      document.getElementById("message").innerHTML = textInput;
      document.getElementById("myImg").src = "church.png";
    }

    if (newInput == "North Again") {
      textInput = "you went to the Abandoned Someplace";
      document.getElementById("message").innerHTML = textInput;
      document.getElementById("myImg").src = "abandoned.png";
    }

    if (newInput == "Help") {
      textInput = "Commands you can use: <ul><li>South</li><li>North</li><li>East</li><li>West</li><li>North Again</li><li>South again</li><li>West Again</li><li>East Again</li><li>North One More</li><li>East Once More</li><li>West Once More</li><li>South Once More</li>";
      document.getElementById("message").innerHTML = textInput;
    }


  }

</script>

Решение B - Чисто JS:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to change the value of the src attribute of the image.</p>
<p><b>Note:</b> The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.</p>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  var img = document.createElement("img");
  img.id = "myImg";
  document.body.appendChild(img);
  document.getElementById("myImg").src = "hackanm.gif";
}
</script>

</body>
</html>

В качестве альтернативы Решение B вам вообще не нужно определять тег <img/> в вашем html и вы можете его создать. от javascript чисто.

Предлагаю прочитать этот документ для более подробной информации здесь

Надеюсь, это поможет вам.

0 голосов
/ 04 апреля 2020

Для этого было бы лучше, если бы вы выбрали подход, основанный на данных. Если у вас есть набор данных, которые вы можете запросить, вы можете получить все, что вам нужно, включая URL-адреса изображений. Вот простой пример для вашего варианта использования:

let data = {
      options: {
        North: {
          message: "you went to the Abandoned Church",
          image: "https://picsum.photos/200/300?random=1"
        },
        South: {
          message: "you went to the Abandoned Someplace",
          image: "https://picsum.photos/200/300?random=2"
        }
      }
    };

Я также создал Codepen для него здесь: https://codepen.io/richjava/pen/poJmKBg

Надеюсь, это поможет.

0 голосов
/ 03 апреля 2020

В html существует тег <img>, позволяющий поместить изображение.

Я думаю, что возможный способ сделать это - создать тег img с пустым sr c, а затем установить src атрибут со ссылкой на изображение, которое вы хотите отобразить.

Здесь вы можете найти пример.

...