Faking CSS :only-child in IE8 with jQuery/JavaScri

2019-05-16 02:52发布

问题:

I have a menu with the :only-child selector so that I can indicate submenus. The :after selector works in IE8 (the only old IE version I have to support), but the :only-child selector does not, so I get an arrow on every menu item, not just on the ones with a submenu.

.menu li > a:after { content: ' ▾'; }
.menu li > a:only-child:after { content: ''; }

What I want is to achieve this using jQuery or JavaScript. I don't want to use Modernizr or Selectivizr and all that stuff, just a single code as an alternative to only-child.

I would really appreciate if you could help me out. I am a newbie when it comes to jQuery and JavaScript, so please explain thoroughly. Thanks!

回答1:

jQuery implements most CSS selectors for you, including :only-child, which makes it very easy to use newer selectors to target elements in older browsers. In fact, Selectivizr depends on another JavaScript library such as jQuery in order to implement selectors directly into CSS.

If you can use jQuery you can simply let jQuery handle the :only-child selector, assigning the only child a class which you can then target with your CSS rule. Unlike Selectivizr, jQuery only lets you use selectors within a script, and not directly in a stylesheet1, so you have to make use of a class name instead.

CSS:

.menu li > a:after { content: ' ▾'; }
.menu li > a.only-child:after { content: ''; } /* Notice the class selector */

JS:

$('.menu li > a:only-child').addClass('only-child');

1 There is a known issue with Selectivizr that prevents you from combining pseudo-classes and pseudo-elements in a selector, so you won't be able to use Selectivizr in this case anyway.



回答2:

For others wondering about this and have the same problem not getting @BoltClock's code to work, it will most probably work if you change $ to jQuery, like this:

jQuery("SELECTOR").exampleMethod("EXAMPLESTRING");