📅  最后修改于: 2023-12-03 14:45:39.414000             🧑  作者: Mango
Primer CSS是由GitHub开发的CSS库,在GitHub的产品和服务中得到了广泛应用。Popover是其中一种常用的UI组件,它类似于下拉菜单,但具有更多的自定义选项和带有方框的箭头,可以更加突出强调选项。
Popover的基本使用很简单。在HTML中,我们需要指定触发popover的元素和它的内容。下面是一个示例代码:
<button type="button" class="btn btn-sm" aria-describedby="my-popover">Popover</button>
<div class="Popover-message Popover-message--right-bottom cx">This is the Popover content</div>
在这个示例中,我们使用了一个按钮元素来触发Popover,它的内容位于一个<div>
元素中。我们需要为这个按钮指定一个aria-describedby
属性,它会指向这个Popover的内容容器。
现在我们需要添加一些CSS来使它生效:
.Popover-message {
display: none;
position: absolute;
z-index: 100;
background: white;
border-radius: 3px;
box-shadow: 0 3px 12px rgba(27, 31, 35, 0.15);
font-size: 14px;
padding: 10px;
line-height: 1.5;
}
.Popover-message--right-bottom {
transform: translate(50%, 100%);
}
在这里,我们为.Popover-message
元素定义了几个基础属性。我们把它们的display
属性设置为none
,这样当Popover没有被触发的时候它是隐藏的。我们还设定了一些其他的样式,包括背景,圆角,阴影和字体大小。
对于右下角的Popover,我们添加了一个.Popover-message--right-bottom
类来定义偏移量。我们使用了CSS中的transform: translate
属性来把组件定位到正确的位置上。
现在,我们需要为标有aria-describedby="my-popover"
的按钮添加一些交互:
document.querySelector('[aria-describedby="my-popover"]').addEventListener("click", function() {
const popover = document.querySelector(".Popover-message");
popover.style.display = "block";
})
我们使用了JavaScript来添加一个点击事件,当用户单击包含aria-describedby="my-popover"
的按钮的时候,我们让Popover出现在屏幕上。很简单吧!
当单击其他区域时,Popover会自动消失:
document.addEventListener("click", function(event) {
const popover = document.querySelector(".Popover-message");
if (!popover.contains(event.target)) {
popover.style.display = "none";
}
});
我们还添加了一个事件监听器,如果用户单击了Popover以外的区域,Popover就会自动消失。
现在,我们将为Popover添加一个右下角的风格。我们将需要做一些更改:
.Popover-message--right-bottom {
position: absolute;
bottom: -10px;
right: 0;
transform: translateX(50%);
}
我们去掉了.Popover-message--right-bottom
类的transform: translate
属性,并添加了position: absolute
、bottom: -10px
和right: 0
属性。
现在,我们就可以在页面中使用一个很漂亮的Popover了,它位于页面的右下角了:
<button type="button" class="btn btn-sm" aria-describedby="my-popover">Popover</button>
<div class="Popover-message Popover-message--right-bottom cx">This is the Popover content</div>
.Popover-message {
display: none;
position: absolute;
z-index: 100;
background: white;
border-radius: 3px;
box-shadow: 0 3px 12px rgba(27, 31, 35, 0.15);
font-size: 14px;
padding: 10px;
line-height: 1.5;
}
.Popover-message--right-bottom {
position: absolute;
bottom: -10px;
right: 0;
transform: translateX(50%);
}
document.querySelector('[aria-describedby="my-popover"]').addEventListener("click", function() {
const popover = document.querySelector(".Popover-message");
popover.style.display = "block";
});
document.addEventListener("click", function(event) {
const popover = document.querySelector(".Popover-message");
if (!popover.contains(event.target)) {
popover.style.display = "none";
}
});
以上就是使用Primer CSS创建右下角Popover的完整代码片段。