Javascript中的图像交换?

时间:2015-03-24 19:02:47

标签: javascript image swap

如何在JavaScript中交换图像?具体来说,我想:从文本框中获取一个新网址,并使用它来更新图片src属性。

这就是我的尝试:

  <h2>Image Swap</h2>
  <img id="kitten" src="http://placekitten.com/g/300/200" title="A kitten" alt="A kitten"><br>
  <input type="text" id="get-img" placeholder="Enter image url here">
  <button id="update-img">Update</button>
  <p>Some possible test examples:</p>
  <ul>
    <li>http://placekitten.com/g/400/320</li>
    <li>http://www.nd.edu/assets/features/2012/features/laetare-2015/standard.jpg</li>
    <li>http://place-hoff.com/400/350</li>
    <li>http://www.placecage.com/c/200/300</li>
  </ul>

  <script>
  var imgchange = document.getElementById("kitten");
  var updateimg = document.getElementById("update-img");
  updateimg.addEventListener("click", myFunction);
  function myFunction(){
      imgchange.setAttribute("src", "document.getElementById("get-img").value");
  }
  </script>

1 个答案:

答案 0 :(得分:2)

你是如此亲密。

唯一需要改变的是: "document.getElementById("get-img").value"document.getElementById("get-img").value

&#13;
&#13;
window.onload = function() {
  var imgchange = document.getElementById("kitten"),
      updateimg = document.getElementById("update-img"),
      imgSelector = document.getElementById("get-img");

  updateimg.addEventListener("click", myFunction);

  function myFunction() {
    imgchange.setAttribute("src", imgSelector.value);
  };
};
&#13;
<h2>Image Swap</h2>
<img id="kitten" src="http://placekitten.com/g/300/200" title="A kitten" alt="A kitten">
<br>
<input type="text" id="get-img" placeholder="Enter image url here">
<button id="update-img">Update</button>
<p>Some possible test examples:</p>
<ul>
  <li>http://placekitten.com/g/400/320</li>
  <li>http://www.nd.edu/assets/features/2012/features/laetare-2015/standard.jpg</li>
  <li>http://place-hoff.com/400/350</li>
  <li>http://www.placecage.com/c/200/300</li>
</ul>
&#13;
&#13;
&#13;