【发布时间】:2017-08-21 06:16:49
【问题描述】:
使用DOM 来更改特定div 的背景比使用document.getElementById('id').style.backgroundImage 更好的方法是什么。
我正在尝试在更改 URL 时更改背景,但我能想到且简单的唯一方法是使用 document.getElementById()
changeBg() {
var urlPath = window.location.pathname.split('/');
switch (urlPath[4]) {
case "Refreshments%20North":
document.getElementById('homeBg').style.backgroundImage = "url('./assets/imgs/spur-2.jpg')";
break;
... more cases
default:
document.getElementById('homeBg').style.backgroundImage = "url('./assets/imgs/background.jpg')";
}
}
我也尝试了Renderer 依赖,但我如何使用它来定位homeBg?
this.renderer.setElementStyle(this.elRef.nativeElement, 'background-image', "url(./assets/imgs/spur-2.jpg)");
模板——基本上只是一个 div
<nav></nav>
<div id="homeBg"></div>
编辑 --
将我的 changeBg() 移至我的 sharedService
public changeBg() {
var urlPath = window.location.pathname.split('/');
switch (urlPath[4]) {
case "Refreshments%20North":
this.homeBg = this.sanitizer.bypassSecurityTrustStyle("url('./assets/imgs/spur-2.jpg')");
break;
default:
this.homeBg = this.sanitizer.bypassSecurityTrustStyle("url('./assets/imgs/background.jpg')");
}
}
在我的配置文件组件中调用changeBg() 服务
ngOnInit() {
this.sharedService.changeBg(); // is this correct?
}
个人资料模板——像这样给我一个错误Cannot read property 'homeBg' of undefined
<div class="home" id="homeBg" [style.background-image]="changeBg?.homeBg"></div>
用route.param.subscribe()改变背景
this.routeSub = this.route.params.subscribe(params => {
this.sharedService.changeBg();
}
【问题讨论】:
-
请添加您的组件模板。
-
你为什么不用 JQuery?
标签: javascript html angular dom