要與超鏈接包裹圖片:
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