将标签添加到图像链接

时间:2018-12-13 16:18:47

标签: html image onclick

我有这个HTML代码段,可在单击图像时打开一个新窗口:

<img src="some_image.jpg" onclick="window.open(this.src)">

这很棒,但是我也想在子窗口的图像下方添加一些文本来描述其内容。是否可以在父窗口的相同标签内进行这样的操作(但是这不起作用)?

<img src="some_image.jpg" onclick="window.open(this.src).document.body.innerText='The image description'">

2 个答案:

答案 0 :(得分:1)

更改onClick来调用函数,如下所示:

<img src="some_image.jpg" onclick="enlarge(this.src, 'The image description')">

现在是函数:

function enlarge(theSrc, theTxt){
    var myWindow = window.open("", "BigWindow", "width=300,height=300");
    myWindow.document.write("<img src='"+ theSrc +"' /><p>"+ theTxt +"</p>");
    myWindow.document.close();
}

答案 1 :(得分:1)

也许是这样吗?

function pop(img) {
  var w=window.open('','popup','width='+img.width+',height='+img.height+50);
  if (w) {
    var html ='<div style="text-align:center">'+
              '<img src="'+img.src+'" alt="'+img.getAttribute('alt')+'" /><br>'+
              '<h1>'+img.getAttribute('alt')+'</h1></div>'; 
    w.document.write(html);
    w.document.close(); 
  }
}

使用

<img src="some_image.jpg" alt="This is a Moose" onclick="pop(this)" />
相关问题