繁体   English   中英

Javascript:如何使Javascript图像链接到页面?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM