如何在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>
答案 0 :(得分:2)
你是如此亲密。
唯一需要改变的是:
"document.getElementById("get-img").value"
至document.getElementById("get-img").value
。
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;