jquery 如何应用url作为css后台上传url?

f45qwnt8  于 2022-11-03  发布在  jQuery
关注(0)|答案(3)|浏览(91)

我需要抓取浏览图像上传URL并将其作为背景封面应用到div中,这是我尝试过的方法,但我没有得到背景图像:
第一个

p3rjfoxz

p3rjfoxz1#

问题是在设置background-image时需要包含url(),因此使用:

$("#top_img").css("background-image", `url(${e.target.result})`);

演示版

第一个

9nvpjoqh

9nvpjoqh2#

您需要使用url()换行图像:
第一个

zdwk9cvp

zdwk9cvp3#

instead of using the filereader use URL.createObjectURL

function readURL(input) {
  if (input.files[0]) {
    const url = URL.createObjectURL(input.files[0])
    $("#top_img").css("background-image", `url(${url}`))
    $("#top_img").css("background-size", "cover")
  }
}

相关问题