在html中, title属性的作用是显示额外的信息,当鼠标移动到元素上时,这些提示信息就会显示出来。然后,title属性的缺点也很明显,一是原始样式太丑,一是鼠标移动到元素上之后,需要等待一段时间才会显示;因此,我们可以使用伪类来解决这两个问题。
实现步骤:
一、首先html布局
<div title="使用css伪类模拟title属性">title属性</div>
<div id="title" onmouseover="onMouseHover(event)" onmouseout="onMouseOut()" data-title="使用css伪类模拟title属性">title属性</div>
二、css样式
使用 ::after 伪元素模拟title属性;
content: attr(data-title) :attr属性通常和自定义属性 data- 配合使用;
#title {
position: relative;
}
#title:hover::before {
content: "";
position: absolute;
bottom: -10px;
z-index: 1100;
width: 0;
border-right: 10px solid transparent;
border-top: 10px solid #0f0;
}
#title:hover::after {
content: attr(data-title);
position: absolute;
bottom: -25px;
z-index: 1000;
text-align: center;
width: max-content;
background: #f00;
color: #fff;
padding: 0 6px;
height: 25px;
line-height: 25px;
font-size: 12px;
}
三、JS 部分
伪类模拟的title属性样子,想要和title本身保持一致(鼠标到哪儿,title浮窗出现在哪儿),那么left值就要和光标的X轴坐标保持一致。
<script>
function onMouseHover(ev) {
document.styleSheets[0].insertRule('#title::before { left: '+ ev.pageX +'px }', 0);
document.styleSheets[0].insertRule('#title::after { left: '+ ev.pageX +'px }', 0);
}
function onMouseOut() {
document.styleSheets[0].deleteRule(0);
document.styleSheets[0].deleteRule(0);
}
</script>
这里使用了 document.styleSheets(可以返回有网页中所用到的样式表组成的数组,但不包括直接嵌在元素里的style,可在控制台上打印查看具体内容) 来修改伪元素中的css属性值,因为这部分内容比较冷门,个人的理解并不是很深,所以在这里不做分析,大家自行百度吧!-_-||~ ~ ~ ~ ~
下图是添加和删除样式的具体项,IE和非IE 用到不同的函数:
以上是使用CSS伪元素,模拟title属性的过程, 那么结果长什么样子呢?? 现在就贴图上来,仅供参考。