简体   繁体   中英

How to change device orientation without CSS and only with JavaScript or jQuery/jQueryMobile?

I have the following HTML Structure:

<div data-role="page" id="pageOne">
        <div data-role="header">
            <h1>Titlu Aplicatie</h1>
        </div>
        <div data-role="main" class="ui-content">
            <h1>Titlu Continut</h1>
            <h2>Subtitlu Continut</h2>
            <p>Text Continut aplicatie</p>
            <div class="change">La click pe acest element schimbam orientarea dispozitivului !</div>
        </div>
        <div data-role="footer">
            <h1>Footer Aplicatie</h1>
        </div>
</div>

and what I want to do is to change the device orientation with JavaScript, jQuery or jQueryMobile only and WITHOUT the use of CSS when the user makes a click on the <div> HTML Element on the page.

I know how to do it with CSS like this:

<script>
        $(document).ready(function () {
            $("div.change").on("click", function () {
                function reorient(e) {
                    var portrait = (window.orientation % 90 == 0);
                    $("body").css("-webkit-transform", !portrait ? "rotate(-90deg)" : "");
                }
                window.onorientationchange = reorient;
                window.setTimeout(reorient, 0);
            });
        });
    </script>

But I want to do it with JavaScript, jQuery/jQuery Mobile only.

Is there by any chance a way of doing it without the use of native code ? Any hint/help is appreciated, thanks in advance !

I have seen in the comments that you are using Cordova for developing mobile application.So my suggestion is to make use of the below Cordova plugin for screen orientation.

https://www.npmjs.com/package/cordova-plugin-screen-orientation

After installing the plugin,now you can change your device orientation when you click on your div with

$("div").on("click",function(){
    screen.lockOrientation('landscape');
});

There are additional usages available in plugin like

// allow user rotate 
screen.unlockOrientation();

// access current orientation 
console.log('Orientation is ' + screen.orientation);

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