How to trigger media query on user demand with jav

2019-03-30 08:43发布

问题:

I have a responsive web page with a different design for different screen sizes, I'm using @mediaquery to change my design. I want to give the user the ability to change the design for smaller or bigger screen sizes even if the screen size didn't change.

Is it possible to trigger a @mediaquery with js without change in sceen size ?

回答1:

Have a look at Enquire.js, a lightweight, pure JavaScript library for responding to CSS media queries.

With it, you could add a class to body based on the width of the screen. If you then organize your CSS based on if the body has a certain class or not. You could use JS to add those classes to the body dynamically based on the users selection.

You could do the same kind of thing with another JS library: MediaClass, the following line of JS:

MediaClass("small-screen", "body(this-max-width: 480px)");

adds the class small-screen to the body tag if the body's width is under 480px. Now you could add some buttons to your site which change the body's width and based on that the layout of your page will change if you have your CSS classes set up that way, instead of "only" based on the screen size. So you would kind of have to refactor your CSS a bit for both of these approaches.