制作一个简单的JavaScript图片库 [英] Making a simple javascript Image gallery

查看:65
本文介绍了制作一个简单的JavaScript图片库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个非常简单的图片库.大多数设计已经完成(使用了JQuery)...但是现在,我正在尝试思考更改图像所需的逻辑.对于这一部分,我认为我只是使用javaScript而不是Jquery来保持简单.我不太熟悉javaScript语法,但这是我的入门尝试.这是创建图片库的可行方法吗?我知道使图像成为背景并不是一个好主意,但是出于测试目的,我不希望裁剪图像-因此将图像设置为背景会修剪图像以使其适合.

I'm trying to make a very simple Image gallery. Most of the design is already complete (used JQuery)...but now I'm trying to think out the logic it takes to get the images to change. For this part I was thinking I would just use javaScript instead of Jquery just to keep it simple. I'm not too familiar with the javaScript syntax but this is my attempt to get started. Is this a feasible way to create an image gallery? I know making the images the background isn't a great idea, but for testing purposes I don't feel like cropping images -- so setting the image as the background trims the images to fit.

我还试图考虑如何将ImageCnt最初设置为零...页面加载时可以使用onload函数将ImageCnt设置为0吗?可以将var传递给next()吗?如果是这样,我可以将当​​前的ImageCnt从onClick传递给该函数.

I was also trying to think about how to set the ImageCnt to zero initially... Can an onload function be used to set the ImageCnt to 0 when the page loads? Can a var be passed into next()? If so, I could pass the current ImageCnt from the onClick to the function.

PS.我已经省略了很多代码以使其易于阅读,但是如果有必要,我可以提供更多代码.

PS. I've omitted a lot of code to keep it simple to read, but I can provide more if it's necessary.

谢谢!这是我的代码:

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

    ImageCnt++;

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

html

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

推荐答案

最重要的是,您需要通过串联("+"运算符)其不同部分来构建背景属性,如下所示;否则,如果将其设为静态字符串,则不会被数组中的值替换.

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>

最后,从onclick返回false,否则您将重新加载页面:

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

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

这篇关于制作一个简单的JavaScript图片库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆