与使用 document.getElementById('id').style.backgroundImage
相比,操作 DOM
来更改特定 div 背景的更好方法是什么。
我试图在更改网址时更改背景,但我能想到且简单的唯一方法是使用 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()
移至我的共享服务
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?
}
配置文件模板 - 像这样给我一个错误无法读取未定义的属性“homeBg”
<div class="home" id="homeBg" [style.background-image]="changeBg?.homeBg"></div>
使用route.param.subscribe()更改背景
this.routeSub = this.route.params.subscribe(params => {
this.sharedService.changeBg();
}
最佳答案
使用绑定(bind)和指令是 Angular2 中的首选方式,而不是命令式 DOM 操作:
<div [style.background-image]="myService.homeBg"
您需要清理 URL 以便 Angular 接受它。 请参阅In RC.1 some styles can't be added using binding syntax了解更多详情。
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;
... more cases
default:
this.homeBg = this.sanitizer.bypassSecurityTrustStyle( "url('./assets/imgs/background.jpg')");
}
}
关于javascript - 在 Angular2 中操作 DOM 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43065059/