解析CSS中的伪元素及其与伪类的区别

2020-05-01 09:52:07易采站长站整理

/* 横向 */    
.plus:before {   
    content: ”;   
    position: absolute;   
    top: 10px;   
    left: 3px;   
    width: 14px;   
    height: 1px;   
    background-color: #fdaa47;   
    display: block;   
}   
/* 纵向 */    
.plus:after {   
    display: block;   
    content: ”;   
    width: 1px;   
    height: 14px;   
    background-color: #fdaa47;   
    position: absolute;   
    left: 10px;   
    top: 3px;   
}   
.opened:after {   
    top: -30px;   
}  

当通过addClass(‘opened’)和removeClass(‘opened’),来切换加减号时:IE8浏览器中效果没有达到预期,部分样式无法覆盖,现解决方案如下:

JavaScript Code复制内容到剪贴板

<div class="parent">   
    <i class="plus"></i>   
</div>   
<script type="text/javascript">   
$(‘.parent’).on(‘click’, function() {   
    var $i = $(this).find(‘i’),   
        className = $i.attr(‘class’);   
    className = /opened/.test(className) ? ‘plus’ : className +’ opened’;   
    $i.replaceWith(‘<i class="’+ className +’""></i>’);   
});   
</script>  

伪类和伪元素的异同
1. W3C CSS 2.1 Selectors
对伪类和伪元素没有做出区分,都是使用一个冒号
比如
伪类:first-child,
伪元素:first-line
PS:在该规范中明确提到了a链接的几种伪类的书写顺序:
Note that the A:hover must be placed after the A:link and A:visited rules, since otherwise the cascading rules will hide the ‘color’ property of the A:hover rule. Similarly, because A:active is placed after A:hover, the active color (lime) will apply when the user both activates and hovers over the A element.