简体   繁体   中英

Change the style of an element when another element has class dynamically applied

I have a rollover menu that has a class applied to <li> elements on hover, which toggles the visibility of a div inside it.

The class is called "cbp-hropen" and is applied when the <li> is hovered.

I'd like to trigger the visibility of another completely separate element called "menuDimmer" when this class is applied to the <li> .

<div class="menuDimmer"></div>
<div id="menu" class="main">
<ul>
    <li>
        MENU
        <div class="cbp-hrsub">content...</div>
    </li>
    <li>
        MENU 2
        <div class="cbp-hrsub">content...</div>
    </li>
</ul>

So I'd like something similar to:

if ($("li").hasClass('cbp-hropen')) {
    $(".menuDimmer").fadeIn(100);
} else {
    $('.menuDimmer').fadeOut(100);
}

(sorry, I know that code is poor but just trying to get the message across)

This has to work dynamically, rather than on page load, as the trigger element itself is only active on hover.

You can use an event to add the class :

$('#id').on('mouseover',function(){
//addclass
} 

then you remove the class of your div

$('#id').on('mouseout',function(){
//removeclass
}

You can use the MutationObserverAPI to listen for DOM changes on specified elements. Take a look at the provided code in this question , as it shows how to use MutationObserver to detect class changes. The MDN doc linked above provides a more general example too.

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