NativeScript中通过CSS设置页面背景图失效,求排查问题
问题:NativeScript页面无法通过CSS设置背景图
我尝试使用CSS为NativeScript页面设置背景图,但未能成功。
HTML代码:
<Page backgroundImage="coverImage"> <GridLayout> <!-- <page-router-outlet></page-router-outlet> --> <Label textWrap="true" class="h1 text-center"> <FormattedString style="font-size: 35rem; font-weight: bold;"> <span text="Welcome to " style="color: white; left: 50%;"></span> <span text="SmartHome" style="color: #F2E3BC;"></span> </FormattedString> </Label> <!-- <Image row="1" col="1"></Image> --> </GridLayout> </Page>
CSS代码:
.coverImage { background-image: url('~/assets/images/IntroductionBackgroundFirst.png'); background-repeat: no-repeat; background-position: center; background-size: cover; }
请问我哪里操作出错了?
解决方案
你犯了两个关键错误:
混淆了NativeScript属性与CSS类的用法
NativeScript的backgroundImage属性是直接接收图片路径的,不是用来指定CSS类名的,你把类名coverImage写到这个属性里完全不对。Page元素不支持Web标准的CSS
background-image属性
NativeScript的Page组件和普通Web元素不同,它不识别CSS里的background-image,得用它专属的属性或NativeScript兼容的样式写法。
正确实现方式
方式一:直接在Page标签设置backgroundImage属性
<Page backgroundImage="~/assets/images/IntroductionBackgroundFirst.png"> <GridLayout> <!-- <page-router-outlet></page-router-outlet> --> <Label textWrap="true" class="h1 text-center"> <FormattedString style="font-size: 35rem; font-weight: bold;"> <span text="Welcome to " style="color: white; left: 50%;"></span> <span text="SmartHome" style="color: #F2E3BC;"></span> </FormattedString> </Label> <!-- <Image row="1" col="1"></Image> --> </GridLayout> </Page>
方式二:通过CSS类复用样式
如果需要复用背景样式,给Page添加类名,NativeScript支持用类来设置背景属性:
CSS代码
.coverImage { background-image: url('~/assets/images/IntroductionBackgroundFirst.png'); background-repeat: no-repeat; background-position: center; background-size: cover; }
HTML代码
<Page class="coverImage"> <GridLayout> <!-- <page-router-outlet></page-router-outlet> --> <Label textWrap="true" class="h1 text-center"> <FormattedString style="font-size: 35rem; font-weight: bold;"> <span text="Welcome to " style="color: white; left: 50%;"></span> <span text="SmartHome" style="color: #F2E3BC;"></span> </FormattedString> </Label> <!-- <Image row="1" col="1"></Image> --> </GridLayout> </Page>
另外要确认图片路径正确:~/assets/images/IntroductionBackgroundFirst.png对应项目根目录下的assets/images文件夹,需确保图片存在且文件名(含大小写)完全匹配,NativeScript对文件名大小写敏感。
内容的提问来源于stack exchange,提问作者Gustavo Gonçalves
相关产品推荐
相关产品推荐

