CSS selector when :target empty

前端 未结 4 1690
我寻月下人不归
我寻月下人不归 2020-12-11 04:03

I need a css3 selector to target an element when the :target equals the id of the element (easy) or when the :target is empty (impossible?). It

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 04:33

    All I can think of is that you have some javascript that checks to see if the hash is empty. If so, it adds a class to the body tag called "noHash". Then, you can use the fact that there is the noHash class available in your CSS rules.

    if (window.location.hash.length <= 1) {
         document.body.className += " noHash";
    }
    

    Then, your CSS could be like this:

    div {
      background: blue;
    }
    div:target, body.noHash div {
      background: red;
    }
    

    If there's any circumstance where a user might add a hash value after the fact, then you may have to watch for that to make sure the noHash class gets removed appropriately.

    Note: you don't have to add the class name to the body tag. You can add it to any parent object that covers all the objects you wish to affect.

提交回复
热议问题