当将
<dialog>
元素与 .show()
一起使用时,它会根据正常的 position
等 CSS 属性进行定位。
是否可以与
.showModal()
有相同的定位?
即使在使用时
dialog:modal {
margin: 0;
position: relative;
}
覆盖浏览器
position: fixed
对话框最终位于左上角(使用 chromium 和 firefox 检查)。
const button = document.getElementById('button');
const b2 = document.getElementById('b2');
const dialog = document.getElementById('dialog');
button.addEventListener('click', () => {dialog.showModal();});
b2.addEventListener('click', () => {dialog.show();});
dialog.addEventListener('click', () => {dialog.close();});
#dialog:modal, #dialog {
margin: 0;
position: relative;
}
#wrapper {
background: #fafafa;
position: relative;
}
<button id="button">open modal</button>
<button id="b2">just show</button>
<div id="wrapper">
<div>Some context below which the dialog should appear.</div>
<dialog id="dialog">click to close</dialog>
</div>
我希望您找到一个仅 CSS 的解决方案,但是如果您将对话框放在包装器 div 中,则可以在显示对话框时使用该 div 的位置来绝对定位对话框:
#dialog {
margin: 0;
position: absolute;
}
<div id="dialog-wrapper">
<dialog id="dialog">click to close</dialog>
</div>
button.addEventListener("click", () => {
const wrapper = document.getElementById("dialog-wrapper");
dialog.style.left = wrapper.offsetLeft + "px";
dialog.style.top = wrapper.offsetTop + "px";
dialog.showModal();
});
实例:
const button = document.getElementById("button");
const b2 = document.getElementById("b2");
const dialog = document.getElementById("dialog");
button.addEventListener("click", () => {
const wrapper = document.getElementById("dialog-wrapper");
dialog.style.left = wrapper.offsetLeft + "px";
dialog.style.top = wrapper.offsetTop + "px";
dialog.showModal();
});
b2.addEventListener("click", () => {
dialog.show();
});
dialog.addEventListener("click", () => {
dialog.close();
});
#dialog {
margin: 0;
position: absolute;
}
<button id="button">open modal</button>
<button id="b2">just show</button>
<div>
<div>Some context below which the dialog should appear.</div>
<div id="dialog-wrapper">
<dialog id="dialog">click to close</dialog>
</div>
</div>
尝试使用
margin-right: 0;
,并根据需要设置 width
和 height
。这对我有用!不需要 position
:已设置为固定。然后该对话框将固定在窗口右侧。