如何在javascript中更改css伪元素

How to change css pseudo elements in javascript?

本文关键字:css 元素 javascript      更新时间:2023-09-26

我想通过javascript或jQuery动态更改以下:before css伪元素的top值。。。我该怎么做?

#buble{
height:70px;
width:980px;
background-color:#bce5a5;
display:none;
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
box-shadow:0px 0px 4px #dadada;
text-indent:35px;
color:#4a8f44;
font-weight:bold;
font-size:14pt;
       }
#buble:before{
content:"";           
display:block;
position:absolute;
top:77px; /* value = - border-top-width - border-bottom-width */
left:555px; /* controls horizontal position */
border-width:11px 7px 0px; /* vary these values to change the angle of the vertex */
border-style:solid;
border-color:#bce5a5 transparent;
width:0;
height:0;
}

据我所知,你不能直接修改伪样式,但你可以通过这种方式将CSS插入DOM的头部

jQuery

$( "div" ).click(function() {
  $('<style>p:before{top:10px}</style>').appendTo('head');
});

检查此演示jsFiddle

使用jQuery,您需要在头中附加样式:

$('<style>#buble:before{top: 50px}</style>').appendTo('head');

查看更多