Making a simple javascript Image gallery

只谈情不闲聊 提交于 2019-12-02 02:49:33

Most importantly, you need to build the background property by concatenating ("+" operator) its different parts, as shown below ; otherwise it won't be replaced by the values from your array if you make it a static string.

Also use the global scope to declare and initialize your image array and counter :

<script>
var myImage= new Array(); 
myImage[0]="penguins.jpg";       
myImage[1]="desert.jpg";
myImage[2]="jellyfish.jpg";
myImage[3]="flower.jpg"; 

var ImageCnt = 0;

function next(){
    ImageCnt++;
    document.getElementById("whiteBox").style.background = 'url(' + myImage[ImageCnt] + ')';
  }
</script>

Finally, return false from onclick otherwise you'll reload the page :

<a href="#" onclick="next();return false;"><img src="next.png"/></a>
geotheory

This is the best example of a simple inline non-jQuery image gallery that I've found, obtained from http://extremestudio.ro/:

<!DOCTYPE html PUBLIC>
<html>
  <head>
    <title>
      Simple and Effective Photo Gallery with HTML and JavaScript
    </title>

    <style type="text/css">
      body {
        background: #222;
        margin-top: 20px;
      }

      h3 {
        color: #eee;
        font-family: Verdana;
      }

      .thumbnails img {
        height: 80px;
        border: 4px solid #555;
        padding: 1px;
        margin: 0 10px 10px 0;
      }

      .thumbnails img:hover {
        border: 4px solid #00ccff;
        cursor:pointer;
      }

      .preview img {
        border: 4px solid #444;
        padding: 1px;
        width: 400px;
      }
    </style>
  </head>

  <body>
    <div class="gallery" align="center">
      <h3>Simple and Effective Photo Gallery with HTML and JavaScript</h3><br/>

      <div class="thumbnails">
        <img onmouseover="preview.src=img1.src" id="img1" src="http://bit.ly/2rz3hy" alt="Image Not Loaded"/>
        <img onmouseover="preview.src=img2.src" id="img2" src="http://bit.ly/1ug1e6" alt="Image Not Loaded"/>
        <img onmouseover="preview.src=img3.src" id="img3" src="http://bit.ly/1yIAYc" alt="Image Not Loaded"/>
        <img onmouseover="preview.src=img4.src" id="img4" src="http://bit.ly/2LHyDW" alt="Image Not Loaded"/>
        <img onmouseover="preview.src=img5.src" id="img5" src="http://bit.ly/2wyHSR" alt="Image Not Loaded"/>
        <img onmouseover="preview.src=img6.src" id="img6" src="http://bit.ly/yRo1i" alt="Image Not Loaded"/>
      </div><br/>

      <div class="preview" align="center">
        <img id="preview" src="http://bit.ly/2rz3hy" alt="No Image Loaded"/>
      </div><br/>
    </div>
  </body>
</html>

The only javascript is embedded in the tags, but could easily be moved to script tags for more flexibility.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!