2012-12-31 44 views
2

我使用JavaScript在刷新时随机更改背景图像。我一直在想这样做则是利用目前background-image URL和内我可以改变背景图片,但是如何打印链接?

<a href=""></a> 

其粘贴在一定DIV,使人们可以下载图片。

背景图像脚本工作,是如下:

var totalCount = 3; 
function ChangeIt() 
{ 
    var num = Math.ceil(Math.random() * totalCount); 
    document.body.background = 'bgimages/'+num+'.jpg'; 
    document.body.style.backgroundRepeat = "repeat";// Background repeat 
} 

很抱歉,如果这是容易的,但我一直无法弄清楚如何做到这一点!任何人都可以将我指向正确的方向吗?

回答

1

让我们假设你有这样的链接中的某处您的文档,并且您希望它指向当前的背景图像:

<a href='#' id='bgDownload'>Download background image</a> 

以下函数ch安格斯现在的链接,在当前的背景和背景本身的 “href” -attribute:

var totalCount = 3; 
function ChangeIt() 
{ 
    var num = Math.ceil(Math.random() * totalCount); 
    document.body.background = 'bgimages/'+num+'.jpg'; 
    document.body.style.backgroundRepeat = "repeat";// Background repeat 

    // change link 
    document.getElementById("bgDownload").href = 'bgimages/'+num+'.jpg'; 
} 

我希望它可以帮助...

+0

Thanks!几个令人敬畏的答案,我能够做到我所需要的。我特别喜欢你把所有的JavaScript都放在头上。非常感谢! – bjornio

1

将一个DIV你的页面上的HTML,并使用切换内容...

document.getElementById("[ID of DIV]").innerHTML = '<a href="' + [link_var] + '">' + [text_var] + '</a>'; 

事情是这样的......

document.getElementById("[ID of DIV]").innerHTML = '<a href="bgimages/' + num + '.jpg">Image #' + num + '</a>'; 
1

试试这个

<a href='javascript:window.location.href=document.body.background'> 
    Download Background 
</a> 
+0

我喜欢这种方法,它工作得很好。谢谢! – bjornio

0

试试这个:

function downloadImage{ 
    window.open(document.body.background,'_blank'); 
    }