在一个div中居中显示toastr通知

5
我正在尝试使我的 toastr通知显示在一个div的中间。我看到了一些建议,比如这个, 但它是基于整个窗口居中,而不是在一个div内居中。
当toastr对表单元素一无所知时,是否可以在表单元素内居中toast通知?
我的最新尝试是在页面中大致居中toast,但我想将其居中在特定的div中。是否可能?如果可能,怎么做?
这是我的居中尝试:
.toast-center {
    top: 50%;
    left: 40%;
}

enter image description here

5个回答

6
您可以尝试创建一个新的div并将其定位在期望的div中心。
然后,您可以使用toastr的positionClass选项,该选项是通知弹出位置。
toastr.options: {
    "positionClass": "your-newly-created-div-class"
}

我不确定如何完成你刚才建议的所有事情。让我自己去尝试一下。谢谢。 - Bob Horn
谢谢你的建议,但我不确定如何让它起作用。 - Bob Horn
@Bob Horn,看看这篇文章,它会解释的。 - Shaiju T
我认为这至少是答案的一半,另一半可能是containerId选项?在toastr.js中检查它的使用此处。如果您使用containerId将参考框架设置为表单,然后使用positionClass将其定位在中间,那么是否有效? - ruffin

5
在toastr.css中添加以下内容:
.toast-top-center {
    top: 12px;
    left:50%;
    margin:0 0 0 -150px;
}

在JavaScript中,可以使用以下代码:
toastr.options = {
    positionClass: 'toast-top-center'
};

如果你的烤面包弹窗有其他宽度,你可以修改上面的CSS代码为其一半宽度。
margin:0 0 0 (here caculate the -width/2 px for yourself)

2
你可以使用jQuery完成这个任务。
在toastr.css中,添加以下内容:
.toast-top-center { 
   top: 12px;   
   margin: 0 auto;  
   left: 50%;   
   margin-left: -150px;
 }

在JS文件中添加以下内容:
toastr.options = {
    positionClass: 'toast-top-center'
};

toastr.success("Your Message Header", "Your Message");

var $notifyContainer = $('#toast-container').closest('.toast-top-center');
if ($notifyContainer) {
   // align center
   var windowHeight = $(window).height() - 90;
   $notifyContainer.css("margin-top", windowHeight / 2);
}

2

在ngx-toastr的最新版本(^14.1.4)中,有一个本地解决方案可解决此问题。如果您查看toast.css文件,您会看到以下内容:

.toast-center-center {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
 }

当您调用toastr通知时,只需在.ts中使用{positionClass: 'toast-center-center' }即可。


1
以下代码片段在使用 "ngx-toastr": "^12.1.0" 的 Angular ~9.1.0 中进行测试。

component-name.ts

import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-component-name',
  templateUrl: './component-name.component.html',
  styleUrls: ['./component-name.component.scss']
})
export class ComponentName implements OnInit {
 
    constructor(private readonly toastrService: ToastrService) { }
    
      ngOnInit(): void {
        this.toastrService.toastrConfig.positionClass = 'toast-top-center';
      }
}

component-name.scss

.toast-top-center { 
    top: 12px;   
    margin: 0 auto;  
    left: 50%;   
    margin-left: -150px;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接