Is there a css selector for selecting an element futherup in the html?

前端 未结 4 1332
温柔的废话
温柔的废话 2020-11-29 13:02

In the following HTML, I want to apply a hover effect to the header h2, upon hover of the image img. Is there a css selector to do that, or another

4条回答
  •  借酒劲吻你
    2020-11-29 13:28

    Update: The subject specifier appears to have been removed from the Editor’s Draft, 6 May 2014 of the Selectors Level 4 specification. This leaves no way to achieve this using CSS.


    Selectors Level 4 introduces the subject specifier which allows:

    !h2 + a img:hover { }
    

    to select the

    .

    Browser support is, AFAIK, currently non-existent.

    You can simulate it in JavaScript (the following is untested, but should give you the idea).

    var img = document.querySelector('h2 + a img');
    img.addEventListener('mouseover', function (e) {
        this.parentNode.previousElementSibling.className += " hovered";
    });
    img.addEventListener('mouseout', function (e) {
        this.parentNode.previousElementSibling.className = this.parentNode.previousElementSibling.className.replace(/\shovered/g, "");
    });
    

提交回复
热议问题