[英]Javascript: How do I make a Javascript image link to a page?
我是Java語言的新手,正在制作HTML網站。
由於我是Java語言的新手,所以我不知道如何顯示圖像,單擊圖像時將其鏈接到頁面。
我知道如何用HTML進行操作,但是由於我是免費主機,所以如果我不對其中有多少個圖像(我將做很多事情)或鏈接到什么位置(將在其中顯示)進行一次更改,在每一頁上),我需要仔細閱讀每一頁。
我需要做的就是在同一標簽上打開頁面。
嘗試這個:
var img = new Image();
img.src = 'image.png';
img.onclick = function() {
window.location.href = 'http://putyourlocationhere/';
};
document.body.appendChild(img);
沒有更多的信息,我會提供這個作為一個相對跨瀏覽器的方式,這將追加一個img
包裹在一個元素a
元素。 這適用於以下(簡單的)HTML:
<form action="#" method="post">
<label for="imgURL">image URL:</label>
<input type="url" id="imgURL" />
<label for="pageURL">page URL:</label>
<input type="url" id="pageURL" />
<button id="imgAdd">add image</button>
</form>
以及以下JavaScript:
// a simple check to *try* and ensure valid URIs are used:
function protocolCheck(link) {
var proto = ['http:', 'https:'];
for (var i = 0, len = proto.length; i < len; i++) {
// if the link begins with a valid protocol, return the link
if (link.indexOf(proto[i]) === 0) {
return link;
}
}
// otherwise assume it doesn't, prepend a valid protocol, and return that:
return document.location.protocol + '//' + link;
}
function createImage(e) {
// stop the default event from happening:
e.preventDefault();
var parent = this.parentNode;
/* checking the protocol (calling the previous function),
of the URIs provided in the text input elements: */
src = protocolCheck(document.getElementById('imgURL').value);
href = protocolCheck(document.getElementById('pageURL').value);
// creating an 'img' element, and an 'a' element
var img = document.createElement('img'),
a = document.createElement('a');
// setting the src attribute to the (hopefully) valid URI from above
img.src = src;
// setting the href attribute to the (hopefully) valid URI from above
a.href = href;
// appending the 'img' to the 'a'
a.appendChild(img);
// inserting the 'a' element *after* the 'form' element
parent.parentNode.insertBefore(a, parent.nextSibling);
}
var addButton = document.getElementById('imgAdd');
addButton.onclick = createImage;
JS小提琴演示 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.