简体   繁体   中英

Replace CSS :hover to :active with JS on touch devices

I want to remove hover effects on touch devices. I know it's better to use hover class for hover effect instead of hover pseudo class since it's easier to remove later on, but since I already coded my site, I can't change all of it now, but I found a good solution that targets all :hover pseudo classes in CSS and replaces them to :active. :active pseudo class works fine for what I want to accomplish, however I have some difficulties with JS code. There are probably some mistakes but I am not able to find them.

 function touch() { if ('ontouchstart' in document.documentElement) { var sheet = document.getElementById("#pagestyle"); if (sheet.cssRules) { for (var i = 0; i < sheet.cssRules.length; i++) { var rule = sheet.cssRules[i]; if (rule.selectorText) { rule.selectorText = rule.selectorText.replace(':hover', ':active'); } } } } }
 .test:hover {}
 <link id="pagestyle" rel="stylesheet" href="css/style.css">

Instead of writing bunch of code in JS, why don't you simply add a rule in stylesheet?

.test:hover,
.test:active {
}

I couldn't understand why you are not adding :active rule as above but if you really only want to put css for those :hover and no-hover devices, then you can use media query like:

@media (hover: hover) {
  .test:hover { }
}
@media (hover: none) {
  .test:active { }
}

There's also:

/* the device does not include any pointing device. */
@media (any-pointer: none) {
    /* ... */
}

You can read more about these on medium

Hope, you find it useful. But in my opinion, this step is really unnecessary. As demonstrated in first code example will be much better than having anything like that.

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