简体   繁体   中英

How to switch desktop view by clicking on simple link on mobile?

On my responsive website (WordPress) I have a link "View desktop version".

I want when I click on that link the desktop view enable and when I click on "View mobile version" it came back to mobile version. Is it possible?

Move any common settings into a separate stylesheet. You should now be left with a stylesheet that only has media queries. In the link tag for the responsive stylesheet add id="dynSS" . Next create a separate stylesheet with only the desktop styles, don't add a link for this stylesheet.

Add this link somewhere in your document.

<a href="javascript:void(0)" id="toggleSS"></a>

Next, the script

Change ssSmURL to the relative url of your responsive stylesheet
Change ssLgURL to the relative url of your non-responsive stylesheet
Change breakPoint to the maximum width of the mobile stylesheet

Basically we dynamically create a new link element with the proper attributes for the style sheet and a unique id so we are not removing common stylesheets.

Then we remove the current stylesheet if it exists and append the new stylesheet.

(function() {
  "use strict";
  window.onload = function() {
    var ssSmURL = 'small.css';
    var ssLgURL = 'large.css';
    var breakPoint = 1000;
    var ssURL;
    var toggle = document.getElementById('toggleSS');

    function loadSS(url) {
      var ss = document.createElement("link");
      ss.href = url;
      ss.rel = "stylesheet";
      ss.id = "dynSS";
      var current = document.getElementById('dynSS');
      if (current) current.remove()
      document.head.appendChild(ss);
      ssURL = url;
      if (ssURL === ssLgURL) {
        toggle.textContent = 'mobile';
      } else {
        toggle.textContent = 'desktop';
      }
    }

    if(window.innerWidth <= breakPoint) {
      toggle.textContent = 'desktop';
    }

    toggle.onclick = function(e) {
      if (ssURL === ssSmURL)
        loadSS(ssLgURL);
      else
        loadSS(ssSmURL);
    };
  }
})();

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