Показывать изображения в порядке нажатия кнопок - PullRequest
0 голосов
/ 30 марта 2020

Я новичок в веб-разработке и пытаюсь создать веб-сайт, который показывает различные флаги при нажатии кнопок.

Я сталкиваюсь с некоторыми проблемами при позиционировании изображения ... Например, когда я нажимаю "C -> A -> D -> B -> A", флаг A появляется перед другими флагами и Я не могу нажать еще раз, чтобы он появился дважды. Вот мои вопросы.

1) Когда я нажимаю на кнопки, изображения отображаются в порядке, а не по той кнопке, которую я нажимаю первым. Есть ли способ сделать первый клик, который появляется первым?

2) Какую функцию или код в CSS / javascript / JQuery можно использовать, если я хочу, чтобы изображение появлялось дважды или более?

Спасибо!

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>

<script>
function showImg( id ) {
        for ( i = 1; i < 10; i++) {
        }
        var obj = document.getElementById( "flag" + id );      
        if (obj != null)
            obj.className = 'show';
}


</script>
<style type="text/css">
    .hide{display:none;}
</style>


<input type="button" onclick="showImg(1)" value="A" >

<input type="button" onclick="showImg(2)" value="B">

<input type="button" onclick="showImg(3)" value= "C">

<input type="button" onclick = "showImg(4)" value= "D">

<input type="button" onclick = "showImg(5)" value= "E">

<input type="button" onclick = "showImg(6)" value= "ANS">

<div class="row">
		<div class="main">
			<div class="screen" position: relative">
				<img id="flag1" src="flag1.jpeg" title="1" class="hide" position="static">
			</div>
			<div position= "relative">
			    <img id="flag2" src="lag2.jpeg" title="2" class="hide">

            <div position= "relative">
			    <img id="flag3" src="flag3.jpeg" title="3" class="hide">
            </div>
            <div position= "relative">
			    <img id="flag4" src="flag4.jpeg" title="4" class="hide">
            </div>
            <div position= "relative">
			    <img id="flag5" src="flag5.jpeg" title="5" class="hide">
            </div>
		    <div position= "relative">
				<img id="flag6" src="flag6.jpeg" class="hide" position="static">
		    </div>
		</div>
	</div>
</div>

</body>
</html>

1 Ответ

1 голос
/ 30 марта 2020

Один из подходов к проблеме состоит в том, чтобы вместо того, чтобы скрывать и показывать элементы (который опирается на те элементы, которые уже находятся в DOM, а затем отображать и скрывать их соответствующим образом, сохраняя их первоначальный порядок), вставлять соответствующие элементы <img /> при щелчке по элементам <button>.

В приведенном ниже HTML я убрал большую часть посторонних HTML, чтобы упростить пример, и преобразовал ваши элементы <input type="button" /> в <button> элементов, что позволяет этим элементам содержать HTML и позволяет использовать сгенерированный контент в псевдоэлементах ::before и ::after:

// here we select all <button> elements that have a "data-src"
// attribute:
const buttons = document.querySelectorAll('button[data-src]'),
    // creating a named function to handle inserting the
    // elements:
    insertImage = function() {
      // the 'this' is passed automatically from the later
      // use of EventTarget.addEventListener() method, here
      // we cache that within a variable:
      let clicked = this,

        // we retrieve the element, via its id, into which
        // we wish to append the elements:
        output = document.getElementById('gallery'),

        // we create an <img> element:
        image = document.createElement('img');

      // we use a template literal to set the 'src'
      // property-value to the 'https' protocol
      // coupled with the data-src attribute-value
      // retrieved via the Element.dataset API:
      image.src = `https://${clicked.dataset.src}`;

      // and append the <img> to the desired element:
      output.append(image);
    };

// here we iterate over the NodeList of <button> elements
// retrieved earlier, using NodeList.prototype.forEach():
buttons.forEach(
  // along with an Arrow function to the attach the
  // insertImage function (note the deliberate lack of
  // parentheses) via the EventTarget.addEventListener()
  // method:
  (btn) => btn.addEventListener('click', insertImage)
);
/*
  using the ::before pseudo-element, with generated
  content, to add text to the button elements that
  have a data-src attribute:
*/
button[data-src]::before {
  content: 'Show image ' attr(value);
}

#gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, 180px);
  grid-gap: 1em;
  align-content: center;
  justify-content: center;
}
<!--
  here we have three <button> elements, each with a data-src
  custom attribute that contains the src of the relevant image:
-->
<button type="button" value="A" data-src="i.stack.imgur.com/4CAZu.jpg"></button>

<button type="button" value="B" data-src="i.stack.imgur.com/SqYhm.gif"></button>

<button type="button" value="C" data-src="i.stack.imgur.com/a9xXV.png"></button>

<div id="gallery"></div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...