我在HTML文件中输入了“ URL”类型。 如何编写JavaScript以从用户输入的URL中获取图像并使用javascript加载
<div class="url-container">
<input type="url" class="form-control" placeholder="Insert image URL" id="image-url">
<button class="btn btn-default" type="submit" id="url_submit">
<i class="material-icons">cloud_download</i>
</button>
</div>
我想在这里加载它:
<img class="materialboxed" src="" id="image" style="">
答案 0 :(得分:1)
您可以仅更改图像的src
属性:
document.getElementById("b").addEventListener("click", e => {
let imageInput = document.getElementById("image-input");
let image = document.getElementById("image");
if (imageInput.value) image.src = imageInput.value;
});
<input type="url" id="image-input">
<button id="b">Change Image</button>
<br>
<img src="" id="image">
或者,使用jQuery:
$("#b").click(e => {
let imageInput = $("#image-input");
let image = $("#image");
if (imageInput.val()) image.attr("src", imageInput.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="url" id="image-input">
<button id="b">Change Image</button>
<br>
<img src="" id="image">
答案 1 :(得分:0)
$('#url_submit').click(function(e) {
e.preventDefault();
$('.materialboxed').attr('src', $('#image-url').val());
}