在做微信小程序时,当遇到需要给某个组件加背景图片时,通常是使用 background-image 这个属性。在以往的网页程序中,直接在这个属性后面加上相对路径或绝对路径,便可以将背景图片显示出来。但是,在微信小程序中却不可以,如果直接设置相对路径或者绝对路径,那么在微信开发者工具中的模拟器确实可以显示出来,但是一到了真机进行调试,却会发现这个属性失效了。目前有两种解决办法:
第一种:将图片路径设置成网络图片地址,需要架设服务器。
第二种:将整张图片转成base64编码的数据,可使用这个在线转换工具进行转换(https://tool.css-js.com/base64.html)。
代码示例:
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAK1ElEQVR4Xu2dfYwcZR3Hv7/ZnVmIW4PttbVgjZYW2oDa6tmbLcVaayPBgiU09SWCGsDr7eKBiAoJiUeiFgOmtHb37lJQkmrUKkh5C1r6Ipbe3HGAMSUtvdqgVLDt0Wp6GHZmZ35md3u11HZ33nd29rm/Nrnn+b18P/PMPvM8v32GIP5irQDFOjuRHATgmF8EArAAHHMFYp6eGMECcMwViHl6sRrBnN+dNmjsYmaeKRHNsICJBE4DlGYgXf0MMGiMgDGAx8qfJeCoxXyAGCMyTdhHuUvH4sK9aQHzgzsnmMXEQhPSImLOgHg2QFP8AcOHwbSXiQYkph3JpPQsdbb/xx/b4VppGsAngC62gEUALQJ4LkCJUORiLgH0AhPtSMD6YyJl7qQbFh4PxbdHJ5EHzP3Dsm6ay4m5C4TFHvP1q/s2idGbSCY3U2e74ZfRIOxEFjDnh6brZH0djBuJ8N4gkvdqkxn/BLBBgbSBcvNf82oviP6RA6z3DbbD5NtAWAFADiLpAGwaAP8GkrRGWdUxHIB91yYjAbhyGy6ZKwh8CwgdrrOJQkfGIEu4X5GSD0fh9t1wwNw/3GaYxlqAvhQFPr7FwPwLOSnfSp3to77ZdGGoYYCZmYzeoesBvg9Am4vYm6HLKAi3KV3qxkYF2xDAnN810yDppwAub1TiYfplxh8UWDnKLdgfpt+yr9ABG33aUjaxEYSpYSfbUH+MQ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