Run javascript/jquery only on screen media, not print

前端 未结 3 905
悲&欢浪女
悲&欢浪女 2020-12-19 01:41

How can I run a jquery function only on @media screen?

Background:

I have a screen.css stylesheet and a print.css styl

相关标签:
3条回答
  • 2020-12-19 02:02

    Any script would be ran when the page loads, so using if (Modernizr.mq('only screen')) {$('h1').text('media screen');} is pointless as it runs your script while you're on @media screen.

    Instead, you have to detect whenever the media query changes, and change the page accordingly. You could use something like enquire.js to do so easily:

    // This is just an example, be more creative!
    
    enquire.register("screen", {
        match: function() { 
            $('#only-show-on-screen').show();
        },
        unmatch: function() {
            $('#only-show-on-screen').hide();
        }
    });
    
    0 讨论(0)
  • 2020-12-19 02:08

    I think you could use Modernizr. Although, there must be a native way to do it in javascript.

    http://modernizr.com/docs/#mq

    I have never tried it but it is something like this:

    if (Modernizr.mq('only screen'))
    {
    ..
    }
    

    beware with old browsers not supporting media queries.

    0 讨论(0)
  • 2020-12-19 02:10

    In latest browsers you can use matchesMedia:

    if (window.matchMedia("screen").matches) {
        ....
    }
    

    If you want to support older browsers too you can use a polyfill like matchMedia.js

    0 讨论(0)
提交回复
热议问题