超链接下载任何img src

时间:2015-12-20 15:07:24

标签: javascript image dom download

好吧,我似乎无法找到任何关于我正在做的事情。

无论如何,我需要设置一个超链接来下载图像。该图片已有ID。

每次用户显示图像时,下载链接都会下载他们输入的图像。

运行代码时,请输入255812作为图像代码。

function myFunction() {
  var x = document.getElementById("imagetxt").value;
  var y = "http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-" + x + ".jpg";

  // Creating an image
  var img = new Image();

  // Defining the function if image loads successfully.
  img.onload = function() {
    document.getElementById("image1").src = y;
  };

  //Defining the function if image fails to load.
  img.onerror = function() {
    alert("Image not found");
  };
  img.src = y;
}
<body align="center">
  <div>
    <img src="http://i.imgur.com/dXo8Fxp.png" width="20%" height="20%">
  </div>
  <div>
    <img src="http://i.imgur.com/jCOLCiU.png" width="8%" height="8%">
  </div>
  <div>
    <input id="imagetxt" size="6" type="text" value="">
  </div>
  <div>
    <input id="btn1" type="button" value="Display" onclick="myFunction()" style="top: 5px; position: relative;">
  </div>
  <div>
    <img id="image1" src="" width="30%" height="30%" style="top: 10px; position: relative;">
  </div>
  <a href="???" id="imageDL" onclick="??">DOWNLOAD THIS</a>

2 个答案:

答案 0 :(得分:1)

摆脱锚标记上的onclick

 <a href="#" id="imageDL" download>DOWNLOAD THIS</a>

在img.onload

中设置锚点的href
img.onload = function() {
    document.getElementById("image1").src = y;
    document.getElementById("imageDL").href = y;
};

答案 1 :(得分:0)

将此添加到myFunction

的末尾
document.getElementById("imageDL").href = y;

&#13;
&#13;
function myFunction() {
  var x = document.getElementById("imagetxt").value;
  var y = "http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-" + x + ".jpg";

  // Creating an image
  var img = new Image();

  // Defining the function if image loads successfully.
  img.onload = function() {
    document.getElementById("image1").src = y;
  };

  //Defining the function if image fails to load.
  img.onerror = function() {
    alert("Image not found");
  };
  img.src = y;
  
  document.getElementById("imageDL").href = y;
}
&#13;
<body align="center">
  <div>
    <img src="http://i.imgur.com/dXo8Fxp.png" width="20%" height="20%">
  </div>
  <div>
    <img src="http://i.imgur.com/jCOLCiU.png" width="8%" height="8%">
  </div>
  <div>
    <input id="imagetxt" size="6" type="text" value="">
  </div>
  <div>
    <input id="btn1" type="button" value="Display" onclick="myFunction()" style="top: 5px; position: relative;">
  </div>
  <div>
    <img id="image1" src="" width="30%" height="30%" style="top: 10px; position: relative;">
  </div>
  <a href="???" id="imageDL" onclick="??">DOWNLOAD THIS</a>
&#13;
&#13;
&#13;