使用javascript从Google图片中获取随机图片 [英] Use javascript to get a random image from Google images
问题描述
我对我的网站有这样的想法,每次访问该页面时,背景都会有所不同。我希望从Google图像中获取任何图片,并使用Javascript将其作为我网站的背景。
I have this idea for my website that every time you visit the page, the background will be different. I want to get literally any picture from Google images and place it as my website's background using Javascript.
基本上每次刷新页面时,脚本都会从中获取随机图片谷歌图像并将其作为背景或至少下载图片。
Basically every time you refresh the page a script will fetch a random picture from Google images and place it as the background or maybe at least download the picture.
我应该怎么做,或者甚至可以吗?
How should I do this, or is it even possible?
推荐答案
可以通过Google图片完成,但需要进行大量自定义,以便脚本按预期运行(包括设置延迟来处理速率限制; Google每个搜索请求的API限制为64个项目这是使用Google Images api的基本示例:
It can be done via Google Images though much customization is required so the script behaves as you intended (including setting up a delay to handle rate-limiting; Google has a rate-limit of 64 items per search request over API) here is a basic example using Google Images api:
<html>
<head>
<title></title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
google.setOnLoadCallback(OnLoad);
var search;
//i suggest instead of this to make keywords list so first to pick random keyword than to do search and pick random image
var keyword = 'mountains';
function OnLoad()
{
search = new google.search.ImageSearch();
search.setSearchCompleteCallback(this, searchComplete, null);
search.execute(keyword);
}
function searchComplete()
{
if (search.results && search.results.length > 0)
{
var rnd = Math.floor(Math.random() * search.results.length);
//you will probably use jQuery and something like: $('body').css('background-image', "url('" + search.results[rnd]['url'] + "')");
document.body.style.backgroundImage = "url('" + search.results[rnd]['url'] + "')";
}
}
</script>
</head>
<body>
</body>
</html>
但我可以建议:来自flickr的随机图片,这是另一个该基本代码(天空是限制):
However may I suggest instead: Random images from flickr, here is another basic code for that (sky is the limit):
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var keyword = "mountains";
$(document).ready(function(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: keyword,
tagmode: "any",
format: "json"
},
function(data) {
var rnd = Math.floor(Math.random() * data.items.length);
var image_src = data.items[rnd]['media']['m'].replace("_m", "_b");
$('body').css('background-image', "url('" + image_src + "')");
});
});
</script>
</head>
<body>
</body>
</html>
这篇关于使用javascript从Google图片中获取随机图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!