要与超链接包裹图片:
function refresh()
{
// we'll be using this element multiple times,
// so caching it here to prevent multiple searches:
var gloria = document.getElementById("gloria"),
// we'll be using this twice, and it's a random-number,
// so again: we're caching it:
source = MyImages[Math.round(Math.random()*3)],
// creating an <a> element:
link = document.createElement('a');
// setting the 'src' property of the <img />:
gloria.src = source;
// setting the 'href' property of the created-<a>:
link.href = source;
// inserting the created-<a> element before
// the <img /> element:
gloria.parentNode.insertBefore(link, gloria);
// adding the <img /> element to the appended-<a>:
link.appendChild(gloria);
}
要插入的图像之前的链接:
function refresh()
{
var gloria = document.getElementById("gloria"),
source = MyImages[Math.round(Math.random()*3)],
link = document.createElement('a');
gloria.src = source;
link.href = source;
// everything as above, but in this case (because
// the <a> is inserted before the <img />) we add
// some text to the <a> element:
link.textContent = source;
gloria.parentNode.insertBefore(link, gloria);
}
插入图像后的链接:
function refresh()
{
var gloria = document.getElementById("gloria"),
source = MyImages[Math.round(Math.random()*3)],
link = document.createElement('a');
gloria.src = source;
link.href = source;
gloria.parentNode.insertBefore(link, gloria.nextSibling);
link.appendChild(gloria);
}
如果您要添加<img />
的src
以外的其他文字,请将图片网址n个对象的阵列与一些相关的文本一起,例如:
var MyImages = [{
'src' : 'path/to/image1.png',
'title' : 'This is image one'
}, {
'src' : 'path/to/image2.png',
'title' : 'And this is image two'
}];
function refresh()
{
var gloria = document.getElementById("gloria"),
// caching the object (rather than a string):
source = MyImages[Math.round(Math.random()*3)],
link = document.createElement('a');
// accessing the 'src' property of the object:
gloria.src = source.src;
link.href = source.src;
// everything as above, but in this case (because
// the <a> is inserted before the <img />) we add
// the relevant text to the <a> element:
link.textContent = source.title;
gloria.parentNode.insertBefore(link, gloria);
}
参考文献:
你想在哪里添加超链接? *围绕图像,之后,之前(在DOM中),完全在其他地方?请注意:我们(通常)愿意提供帮助,但您需要花点时间澄清您的问题,向我们解释您希望和期望的结果。而且,如果可能的话,向我们展示你试图实现这个理想的结果。 – 2015-02-10 11:51:30
“添加超链接到图片”是什么意思?你的意思是让图片本身可以点击,点击后转到另一个网页?或者你只是想在上面覆盖文字超链接?或者你想要一个'
做一些像imagearray:[ [“images/1.jpg”,“yourlink”,“Your text goes here”], [“images/2.jpg”,“yourlink”,“Your text goes here”] , [“images/3.jpg”,“yourlink”,“你的文字就在这里”] ]让我知道它是否不起作用 – 2015-02-10 12:01:45