<!DOCTYPE html>
<html>
<head>
<title>角标Demo</title>
<!-- 替换成自己的JQuery路径 -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
/* 给目标矩形添加基本样式 */
#target{
width:100px;
height:50px;
border:1px solid gray;
}
/* 【重要】通过伪元素after设置角标 */
.cornerMark::after{
content: attr(data-cm-content); /* 读取目标元素上data-cm-content属性的值,从而实现灵活设置内容 */
display: block; /* 块级元素,让宽高属性生效 */
width: 30px; /* 根据个人需要调整 */
height: 16px;
line-height: 16px; /* 与height值保持一致,以实现文字垂直居中 */
border-top-left-radius: 16px; /* 圆角效果 */
border-top-right-radius: 16px;
border-bottom-right-radius: 16px;
padding: 0 5px;
color: white;
font-size: 12px; /* 尺寸小于12px时无效,可结合scale实现更小的效果 */
transform: scale(0.9);
border: 2px solid white;
background-color: red;
position: absolute; /* 绝对定位,使其居于目标元素右上角。注意,目标元素必须已定位(position不是默认值static) */
top: -8px;
left: calc(100% - 10px); /* 角标左侧与目标元素相交10px */
z-index: 10; /* 避免被其它层级的元素遮挡。该值可根据需要调整 */
}
</style>
</head>
<body>
<div id="target"></div>
<script>
/**
* 给指定元素的右上角设置指定内容的角标
* @param ele 目标html元素
* @param text 角标的内容
* PS:该方法会给指定html元素ele设置定位为relative(如果该元素未定位)
*/
function genCornerMark(ele,text){
if($(ele).css('position') === 'static'){
$(ele).css('position','relative');
}
$(ele).addClass('cornerMark').attr('data-cm-content',text);
}
/**
* 清除所有的角标
*/
function clearCornerMark(){
$(".cornerMark").removeClass("cornerMark");
}
// 测试代码
genCornerMark($("#target")[0], '测试');
</script>
</body>
</html>
