How do I change image A when hovering over image B without JavaScript only CSS

后端 未结 4 2111
梦谈多话
梦谈多话 2020-12-20 06:32

I would like to know how to update image A when I hover over image B using only CSS, is it possible? if not how will I do that using only pure JavaScript (no library). But c

4条回答
  •  暖寄归人
    2020-12-20 06:56

    This depends entirely on your mark-up, as I pointed out in the comments. In the absence of seeing any mark-up to work with, I can only post some general suggestions; however it's important to note that the element you want to affect (F) must appear later in the DOM (be a child of the element F, or be subsequent sibling, or descendant of a subsequent sibling) than the element E with which you want to interact.

    That said, the following approaches will work, with the associated mark-up:

    Sibling-based selection:

    Hovering over the first img inside of #a toggles the display of the subsequent img elements, using the E ~ F (general sibling) combinator:

    ​​​​​ #a img.second, #a img.first:hover ~ img.second { display: none; } #a img:hover ~ img.first { display: none; } #a img:hover ~ img.second { display: inline-block; }​

    JS Fiddle demo.

    Hovering over #a changes switches the display of the .first and .second images inside of #b, using the E + F (immediate sibling) combinator:

    ​​​​​​​​​​​​​​​​​ #a,#b { float: left; border: 1px solid #000; padding: 0.2em; } img.second { display: none; } #a:hover + #b img.first { display: none; } #a:hover + #b img.second { display: inline-block; }​

    JS Fiddle demo.

    Descendant-based selection:

    Using the E F general descendant combinator (I'm not actually entirely sure a space character is a combinator, but regardless...it's based on F being a descendant of E):

    ​ #a img.second { display: none; } #a:hover img.first { display: none; } #a:hover img.second { display: inline-block; }

    JS Fiddle demo.

    Using E > F the immediate-child/immediate-descendant combinator:

    ​ div { display: inline-block; } img { display: none; border: 1px solid #000; padding: 0.2em; } #a > img { display: inline-block; } #a:hover img { display: inline-block; }​

    JS Fiddle demo.


    There's also the chance to use pseudo-elements and css-generated content (in compliant/up-to-date browsers):

    ​ #a { width: 200px; height: 400px; background-image: url(http://www.lorempixel.com/200/400/people); background-repeat: none; background-position: 50% 50%; position: relative; } ​#a:hover::after { content: url(http://www.lorempixel.com/200/400/animals); width: 100%; height: 100%; position: absolute; top: 0; left: 100%; }​

    JS Fiddle demo.

提交回复
热议问题