简体   繁体   中英

CSS Transition on newly created psuedo element

I want to create a fade effect on a pseudo element but am having difficulty as i cannot use javascript on this element.

I have an example of something similar to what i am trying to do here but i cannot get the element to fade in as transitions do not seem to work when the element is created.

https://codepen.io/anon/pen/wrxPXJ

.hoverhere.dim::before {
    content: '\A';
    position: absolute;
    width: 100%; 
    height:100%;
    top:0; 
    left:0;
    background:rgba(0,0,0,0.8);
    opacity: 1;
    transition: opacity 1s;
 }

I am adding a class to a div so that the pseudo element is created after matching with the above css however cannot work out how to animate this.

I can probably get it to work without psuedo elements like below:

https://codepen.io/anon/pen/Oxwzvv

However was wondering if there is a way without changing my markup to include an empty div.

I guess you're saying you want this?

 $('.hoverhere') .mouseenter(function() { $(this).addClass('dim'); }) .mouseleave(function() { $(this).removeClass('dim'); }); 
 .hoverhere { width: 100%; height: 40px; background: red; color: white; text-align: center; } .hoverhere::before { content: '\\A'; position: absolute; width: 20%; height: 100%; top: 0; left: 0; background: rgba(0, 0, 0, 0.8); opacity: 0; visibility: hidden; transition: all 1s ease-out; } .hoverhere.dim::before { opacity: 1; visibility: visible; transition: opacity 1s ease-out; } 
 <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <p>RANDOM TEXT HERE</p> <div class="hoverhere">HOVER ON ME</div> <p>MORE RANDOM TEXT HERE</p> 

What it needed was to have a starting point established for the opacity .


If this is just for hovering, you don't need the JS at all.

 .hoverhere { width: 100%; height: 40px; background: red; color: white; text-align: center; } .hoverhere::before { content: '\\A'; position: absolute; width: 20%; height: 100%; top: 0; left: 0; background: rgba(0, 0, 0, 0.8); opacity: 0; visibility: hidden; transition: all 1s ease-out; } .hoverhere:hover::before { opacity: 1; visibility: visible; transition: opacity 1s ease-out; } 
 <p>RANDOM TEXT HERE</p> <div class="hoverhere">HOVER ON ME</div> <p>MORE RANDOM TEXT HERE</p> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM