问题描述
我正在创建一个用户注册页面,我希望用户能够输入图像URL,然后在保留的div中预览图像(已在其中包含默认图像,该图像已由给定类应用).用于用户图像显示的我的HTML是:
I'm creating a user signup page and I want the user to be able to enter an image URL and then preview the image in a reserved div (which has a default image in it already, applied by a given class). My HTML for the user image display is:
<div id="user-image-preview" class="col-md-4 col-sm-12 user-image-preview"> </div>
<button id="preview-image">Preview image</button>
id为"user-image-preview"和类"user-image-preview"的CSS为:
The CSS for id'user-image-preview' and class 'user-image-preview' are:
#user-image-preview {
height: 300px;
width: 300px;
border-radius: 50%;
position: absolute;
left: 200px;
top: 150px;
background-size: cover;
}
.user-image-preview {
background-image: url("https://cdn1.iconfinder.com/data/icons/unique-round-blue/93/user-512.png");
background-size: cover;
}
这是用户输入图像URL的表单的输入部分:
Here is the input part of the form where user inputs image URL:
<div class="form-group">
<i class="fa fa-picture-o" aria-hidden="true"></i>
<label for="img">Image</label>
<input id="user-image-set" type = "text" class ="form-control" placeholder = "Enter image URL" name = "image">
</div>
<button id="submit-login" type ="submit" class="btn btn-primary btn-lg disabled">Signup</button>
然后我写了下面的jQuery来删除默认图像(class ="user-image-preview"),然后在输入字段中添加任何内容:
And then I wrote the following jQuery to remove the default image (class="user-image-preview") and then add whatever is in the input field:
$("#preview-image").on("click", function() {
var newUserImage = $('#user-image-set').val();
$("#user-image-preview").removeClass("user-image-preview");
$("#user-image-preview").css("background-image", "url('newUserImage')");
console.log(newUserImage)
})
(我添加console.log只是为了检查我是否正确捕获了我所在的变量).
(I added the console.log just to check if I am capturing the variable correctly which I am).
我认为在函数的URL部分使用引号会引起问题,但我无法弄清楚引用此变量的正确方法是什么.
I presume the is a problem with my use of quotes within the URL part of the function, but I can't quite work out what the correct way to cite this variable is.
推荐答案
由于newUserImage
是变量,因此您不必将其放在引号中''所以改变这一行
As newUserImage
is a variable, you don't have to put it in quotes ''so change this line
$("#user-image-preview").css("background-image", "url('newUserImage')");
到
$("#user-image-preview").css("background-image", "url(" + newUserImage + ")");
这篇关于使用变量URL(jQuery)设置div的背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!