CSS for touch/no touch with small devices to be marked as no-touch

CSS for touch/no touch with small devices being marked as no-touch too

我正在使用 modernizer 将 touch/no-touch 添加到我的页面,我目前有以下 css:

.touch .desktop_only {
       display: none !important;
}
.no-touch .mobile_only {
       display: none !important;
}

我曾经用过:

@media only screen and (max-width: 1024px){
    .desktop_only {
       display: none !important;
    }
}
@media only screen and (min-width: 1025px){
    .mobile_only {
       display: none !important;
    }
}

我正在尝试将它们合并,以便 1024 像素和更小的设备也被归类为触摸设备,而不是非触摸设备...

与此同时,我也 运行 遇到了一个问题,它会在瞬间同时加载 desktop/mobile 内容。

知道如何做到这一点,我相信它会很简单,但我根本无法解决。

我尝试了下面的代码,但是由于 "intial"

,这只会让很多 css 变得奇怪
@media only screen and (max-width: 1024px){
    .desktop_only {
       display: none !important;
    }
    .touch .desktop_only {
           display: none !important;
    }
    .no-touch .mobile_only {
           display: initial !important;
    }
}
@media only screen and (min-width: 1025px){
    .mobile_only {
       display: none !important;
    }
    .touch .desktop_only {
           display: initial !important;
    }
    .no-touch .mobile_only {
           display: none !important;
    }
}

您可以使用 javaScript/jQuery 检测触摸设备并相应地添加或删除 class。

<script>
$(document).ready(function() {
    var ua = navigator.userAgent;
    function is_touch_device() { 
        try {  
            document.createEvent("TouchEvent");  
            return true;  
        } catch (e) {  
            return false;  
        }  
    }

    if ((is_touch_device()) || ua.match(/(iPhone|iPod|iPad)/) 
    || ua.match(/BlackBerry/) || ua.match(/Android/)) {
        $('html').addClass('touch');
    } else {
         $('html').addClass('no-touch');
    }
});
</script>