角度2:CSS 目标选择器不起作用



我正在尝试按照此示例(http://www.webdesignerdepot.com/2012/10/creating-a-modal-window-with-html5-and-css3/)在Angular2项目中创建自己的模态。

在我的 html 模板中,我有

 <a href="#openModal" (click)="openDialog()" >Open Modal again</a>
<div id="openModal" class="modalDialog">
    <div>
        <a href="#close" title="Close" class="close">X</a>
        <h2>Modal Box</h2>
        <p>This is a sample modal box that can be created using the powers of CSS3.</p>
        <p>You could do a lot of things here like have a pop-up ad that shows when your website loads, or create a login/register form for users.</p>
    </div>
</div>

我之所以将(click)="openDialog()"添加到<a> href="#openModal"是因为未注册到路由器。我必须防止方法中的默认行为。

而且,在相应的scss文件中,我有

.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0,0,0,0.8);
    z-index: 99999;
    opacity:0;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    pointer-events: none;
}
.modalDialog:target {
    opacity:1;
    pointer-events: auto;
}
.modalDialog > div {
    width: 400px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: #fff;
    background: -moz-linear-gradient(#fff, #999);
    background: -webkit-linear-gradient(#fff, #999);
    background: -o-linear-gradient(#fff, #999);
}

在组件的 ts 文件中,我将以下方法绑定到我链接的 click 事件。

openDialog(){
    event.preventDefault();
}

上面的代码片段是在用户单击链接后弹出一个模态;但是,这样做后什么也没发生。我认为 css .modalDialog:target选择器实际上由于某些原因不起作用,因此不透明度没有改变。

通过调用preventDefault()可以阻止该元素成为#hash的目标。

您必须删除preventDefault()调用才能将#openModal设置为点击时网址哈希的目标,并使用:target选择器。

OP表示这是有效的:

openDialog () {
    location.hash = "#openModal"
    event.preventDefault()
}

最新更新