CSS:带标题的内容之前/之后

时间:2014-03-12 13:10:18

标签: css title pseudo-element

我能做到

div:after {
  content: "hello"
}

但是我可以使用带有标题的hello文本,这样当我用鼠标悬停它时,会显示标题吗?

由于

3 个答案:

答案 0 :(得分:17)

您不需要伪元素:

JSFiddle Demo

<p class="hover-me" title="I Show up on Hover">Some Text</p>

但是,如果需要使用伪元素

JSFiddle Demo (2)

<强> HTML

<p class="hover-me" data-title="I Show up on Hover">Some Text</p>

<强> CSS

p {
    background:lightblue;
    padding:15px;
    margin:15px;
    position: relative;
}

p:hover:after {
    position: absolute;
    content:attr(data-title);
    left:0;
    top:0;
    width:200px;
    height:1.25rem;
    background-color: blue;
    color:white;
}

答案 1 :(得分:1)

解决方法是使用两个伪元素。

例如 :: after 是主要元素, :: before 将在悬停时显示,并且就像标题一样。

此外,您可以使用javascript或jQuery代码检测伪元素上的鼠标事件。

Demo

Bellow是演示说明:

&#13;
&#13;
$('.alert').on('mousemove', function(e) {
    if (e.offsetX > (this.offsetWidth - 42)) { //42 is the ::after element outerWidth
        $(this).addClass('hover');
    } else {
        $(this).removeClass('hover');
    }
}).on('mouseleave', function(e) {
    $(this).removeClass('hover');
}).on('click', function(e) {
    if (e.offsetX > (this.offsetWidth - 42)) { //42 is the ::after element outerWidth
        $(this).remove();
    }
});
&#13;
.alert {
    padding: 15px;
    margin: 50px 0 20px;
    border: 1px solid transparent;
    border-radius: 4px;
    position: relative;
    color: #a94442;
    background-color: #f2dede;
    border-color: #ebccd1;
    font-size: 0.85em;
    transition: all 1s;
}
.alert::after, .alert::before {
    content: 'X';
    position: absolute;
    right: 0;
    top: 0;
    width: 40px;
    height: 100%;
    font-size: 0.85em;
    padding: 0;
    line-height: 40px;
    text-align: center;
    font-weight: 900;
    font-family: cursive;
    cursor: pointer;
}
.alert::before {
    display: none;
    content: 'This is a Title';
    top: -105%;
    width: auto;
    border: inherit;
    border-radius: inherit;
    padding: 0 0.4em;
    background: rgba(0, 0, 0, 0.48);
    color: white;
}
.alert.hover::after {
    color: white;
    filter: sepia(10%);
    transform: scale(1.1);
    border-radius: inherit;
    border: inherit;
    background: inherit;
}
.alert.hover::before {
    display: inline-block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="alert">
  <strong>Hover</strong> over X to display the title.
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用:

div:hover:before{
  content: "Bye";
          }