我需要在网页上显示一个随机图像(在某些特定类别或标签中)。
有没有这样的服务可以让我通过php或javascript从中获取随机图像?
我认识一些人,但他们的知识库很小。
问题:
我需要在我的网页上显示一个随机图像(在某些特定类别或标签中)。
解决方案:
可以使用setInterval()
和random()
方法在javascript中实现图像的随机旋转。setInterval()
方法以指定的时间间隔(以毫秒为单位)调用函数或计算表达式,random()
方法返回一个介于0(包含)和1(排除)之间的随机数。让我来解释一下这个旋转是如何工作的。(已测试)
假设你有四个图像,像这样:
- 第一张图片.png
- 第二张图片.png
- 第三页.png
- 第四张图片.png
HTML
这是一个简单的图像标签来显示图像
<!--display an image initially-->
<img id="myImage" src="firstimage.png" />
JAVASCRIPT
首先获取图像标签的id
// Get the id of image tag
var myImage = document.getElementById("myImage");
然后将所有图像的路径存储在一个数组中,如下所示:
// store the path of all the images in an array
var imageArray = ["firstimage.png", "secondimage.png", "thirdimage.png", "fourthimage.png"];
然后编写一个函数,在相等的时间间隔内旋转图像,如下所示:
// function to rotate images after specified interval(3 seconds in this case)
function imageRotation(){
// since we have four images hence we've taken 4 as a multiplier to get random number between 0 and 3
var imageIndex = Math.floor(Math.random() * 4);
// set appropriate attribute
myImage.setAttribute("src", imageArray[imageIndex]);
}
注意,上面的imageRotation()
函数使用random()
函数来生成0到3之间的随机数,并且它决定接下来要选择哪个图像。
现在用适当的参数调用setInterval()
函数,如下所示:
// imageRotation will be called in every 3 seconds
var everyInterval = setInterval(imageRotation, 3000);
旁注:setInterval()
方法将继续调用函数,直到调用clearInterval()
或关闭窗口。因此,为了在任何时间点停止这种情况,我们有clearInterval()
函数。例如,如果你想要一种行为,当用户将鼠标悬停在图像上时,旋转将停止,那么你可以这样做:
// when the user hovers his/her mouse over an image, the rotation will stop
myImage.onhover = function(){
clearInterval(everyInterval);
}
这是完整的工作代码,
<html>
<head>
<title>Page Title</title>
</head>
<body>
<!--set an image initially-->
<img id="myImage" src="firstimage.png" />
<script>
window.onload = function(){
// Get the id of image tag
var myImage = document.getElementById("myImage");
// store the path of all the images in an array
var imageArray = ["firstimage.png", "secondimage.png", "thirdimage.png", "fourthimage.png"];
// function to rotate images after specified interval(3 seconds in this case)
function imageRotation(){
// since we have four images hence we've taken 4 as a multiplier to get random number between 0 and 3
var imageIndex = Math.floor(Math.random() * 4);
// set appropriate attribute
myImage.setAttribute("src", imageArray[imageIndex]);
}
// imageRotation will be called in every 3 seconds
var everyInterval = setInterval(imageRotation, 3000);
// when the user hovers his/her mouse over an image, the rotation will stop
myImage.onhover = function(){
clearInterval(everyInterval);
}
};
</script>
</body>
</html>
编辑:
问题:
有没有这样的服务可以让我通过php或javascript从中获取随机图像?
解决方案:
要获得大型图像存储库,您可以使用TinEye API、flickr API或BOSS Search API。自2010年11月1日起,Google的API正式被弃用。