как изменить изображение в JavaScript, используя массив источников изображений

#javascript #html #css

#javascript #HTML #css

Вопрос:

вот мой html-код:

 var picList = ["http://www.acidre.com/dummy/16:9x1080", "http://www.nexusnetsolutions.com/image/product.png", "http://lehmanlaw.mn/wp-content/uploads/2016/03/vga-1.png"];

 function nextPic() {
   var cur = 0;
   var f = 0;
   var x = document.getElementById("pics").src;
   for (cur = 0; cur < picList.length; cur  ) {
     if (x == picList[cur]) {
       f = 1;
       break;
     }
   }
   if (f == 1) {
     if (cur < picList.length - 1) {
       document.getElementById("pics").src = picList[cur   1];
     }
   }
 }

 function prevPic() {
   var cur = 0;
   var f = 0;
   var x = document.getElementById("pics").src;
   for (cur = 0; cur < picList.length; cur  ) {
     if (x == picList[cur]) {
       f = 1;
       break;
     }
   }
   if (f == 1) {
     if (cur > 0) {
       document.getElementById("pics").src = picList[cur - 1];
     }
   }
 } 
 header {
  position: absolute;
  display: block;
  background: cyan;
  height: 150px;
  width: 1350px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
h1 {
  color: white;
  position: absoute;
  padding-left: 450px;
  padding-top: 15px;
  font-family: 'Cabin', sans-serif;
  font-size: 50px;
  font-variant: small-caps;
}
#pics {
  margin-top: 170px;
  margin-left: 270px;
}
#bnext {
  position: absolute;
  margin-left: 100px;
  margin-top: 400px;
  width: 80px;
}
#bprev {
  position: absolute;
  margin-left: -980px;
  margin-top: 400px;
  width: 80px;
} 
 <header>
  <h1>Image Showcase</h1>
</header>
<img id="pics" src="http://lehmanlaw.mn/wp-content/uploads/2016/03/vga-1.png" alt="Forms" width="800px" height="500px"></img>
<button id="bnext" type="button" onclick="nextPic()">Next</input>
  <button id="bprev" type="button" onclick="prevPic()">Previous</input> 

при нажатии на кнопки next и previous ничего не происходит. не могу понять, почему.. было бы очень полезно, если кто-нибудь даст решение

Комментарии:

1. Если ваш вопрос является ответом, пожалуйста, отметьте правильный

Ответ №1:

Почему вы хотите проверить источник изображений?

 if (x == picList[cur]) {
   f = 1;
   break;
 }
 

и я не вижу, где вы изменили свое изображение, за исключением некоторых условий:

  if (cur ...) {
   document.getElementById("pics").src = ...;
 }
 

Все это не нужно. Вам нужно только переключать изображения на основе содержимого массива и добавлять свои условия для защиты от «неопределенного» индекса массива.

Вот простой рабочий пример кода:

 <!DOCTYPE html>
<html>
<body>
<header>
  <h1>Image Showcase</h1>
</header>
<img id="pics" src="http://lehmanlaw.mn/wp-content/uploads/2016/03/vga-1.png" alt="Forms" width="800px" height="500px"></img>
<button id="bnext" type="button">Next</input>
  <button id="bprev" type="button">Previous</input>

<script>
(function(){
 var images = ["http://www.w3schools.com/images/w3schoolscom_gray.gif", "none"];
 var index = 0;
 function prevImage() {
  index--;
  index = index < 0 ? 0 : index;
  return images[index];
 }

 function nextImage() {
  index  ;
  index = index >= images.length ? images.length - 1 : index;
  return images[index];
 }

 document.querySelector("#bprev").onclick= function() {
  document.querySelector("#pics").src = prevImage();
 }

 document.querySelector("#bnext").onclick= function() {
  document.querySelector("#pics").src = nextImage();
 }

})();

</script>
</body>
</html>
 

Ответ №2:

 var picList = ["http://allwebco-templates.com/support/picts/sample-image.jpg",
  "http://mfs1.cdnsw.com/fs/cc0/normal/cx0ms-193.jpg",
  "https://freethumbs.dreamstime.com/114/big/free_1145336.jpg",
  "http://images.all-free-download.com/images/graphicthumb/male_lion_193754.jpg"
];

var currentIndex = 0;
var pic = document.getElementById("pics");

function nextPic() {
  pic.src = picList[(currentIndex  ) % picList.length];
}

function prevPic() {
  if (currentIndex == 0)
    currentIndex = picList.length - 1;
  else
    currentIndex = currentIndex - 1;

  pic.src = picList[currentIndex];
} 
 header {
  position: absolute;
  display: block;
  background: cyan;
  height: 150px;
  width: 1350px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
h1 {
  color: white;
  position: absoute;
  padding-left: 450px;
  padding-top: 15px;
  font-family: 'Cabin', sans-serif;
  font-size: 50px;
  font-variant: small-caps;
}
#pics {
  margin-top: 170px;
  margin-left: 270px;
} 
 <!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Image Showcase</title>
  <link rel="stylesheet" type="text/css" href="imgShow.css"></link>
  <script src="imgShow.js"></script>
</head>

<body>
  <header>
    <h1>Image Showcase</h1>
  </header>
  <img id="pics" src="http://allwebco-templates.com/support/picts/sample-image.jpg" alt="Forms" width="300px" height="200px" /></img>
  <button id="bnext" type="button" onclick="nextPic()">Next</input>
    <button id="bprev" type="button" onclick="prevPic()">Previous</input>
</body>

</html> 

Ответ №3:

Кнопка Html для вас неправильная, измените ее на .

 <button id="bnext" type="button" onclick="nextPic()">Next</button >
<button id="bprev" type="button" onclick="prevPic()">Previous</button>
 

Комментарии:

1. Это приведет к появлению ошибки, когда cur == picList.length - 1

2. @Weedoze Я так не думаю, не могли бы вы просветить, как?

3. О, вы просто заменяете внутри своего кода? Я не видел, чтобы он обрабатывал код при нажатии последнего / первого элемента

Ответ №4:

Вот пример, позволяющий сделать это немного по-другому. Одна вещь заключается в том, что я удалил вызов обратно в JS-файл вместо вызова prevPic() nextPic() inline .

JS

 var picList = [
        'http://orig10.deviantart.net/78b3/f/2009/025/0/0/0044146485035ccdcc4f99a681af80c6.jpg',
        'http://pre15.deviantart.net/39b2/th/pre/i/2012/221/3/3/square_2_by_lilith1995-d5ag32b.jpg',
        'http://img15.deviantart.net/4e63/i/2010/188/6/c/fly__fly_away___sqaure_crop_by_tagirocks.jpg',
        'http://img13.deviantart.net/036f/i/2016/287/c/3/harley_quinn_by_mz09-dakslb5.jpg',
    ];


function imageShowCase(list) {

    var cur = 0;
    var img = document.getElementById('pics');

    /* Use controls element to delegate from buttons */
    var controls = document.getElementById('controls');

    /* Update the image src */
    var update = function(index) {
        img.src = list[index];
    };

    /* Count up on the current index, reset to 0 if reaced the total length of array */
    var next = function() {
        cur = (cur < list.length - 1) ? (cur   1) : 0;
    };

    /* Count down, reset to length of array, minus 1 */
    var prev = function() {
        cur = (cur === 0) ? (cur = list.length - 1) : cur - 1;
    };

    /* Delegate to the controls elememt */
    controls.addEventListener('click', function(e) {

        /* Stop any event bubling */
        e.stopPropagation();

        /* Check which element was clicked by comparing IDs */
        if      (e.target.id === 'bnext') { next(); }
        else if (e.target.id === 'bprev') { prev(); }
        else { return; }

        /* Render the image with new src */
        update(cur);

    }); 
}

imageShowCase(picList);
 

CSS

 header{
    display: block;
    background: cyan;
    height: 150px;
    width: 1350px;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
h1{
    color: white;
    position: absoute;
    padding-left: 450px;
    padding-top: 15px;
    font-family: 'Cabin', sans-serif;
    font-size: 50px;
    font-variant: small-caps;
}

.wrapper {
    margin: 0 auto;
    max-width: 400px;
}

#pics{
    width: 100%;
}

#bnext{
    width: 80px;
}
#bprev{
    width: 80px;
}
 

HTML

 <header>
    <h1>Image Showcase</h1>
</header>
<div class="wrapper">
    <div id="controls">
            <button id="bprev" type="button">Previous</button>
            <button id="bnext" type="button">Next</button>
    </div>
    <br>
    <img id="pics" src="http://orig10.deviantart.net/78b3/f/2009/025/0/0/0044146485035ccdcc4f99a681af80c6.jpg"/>
</div>