简体   繁体   中英

How to set CSS on body tag to rotate a page using JavaScript

I found the following code while reading a related question at this page: Rotate a webpage clockwise or anticlockwise

html {
     -webkit-transform: rotate(180deg);
     -moz-transform: rotate(180deg);
}

--

My question is how do I set this CSS via JavaScript?

When a visitor clicks on an image, I want to use JavaScript to modify the HTML tag's style using the settings above.

Thanks in advance.

The easiest way to do this is by putting this in a class, and assigning that class dynamically using JavaScript:

CSS:

html.rotateme {
     -webkit-transform: rotate(180deg);
     -moz-transform: rotate(180deg);
}

JavaScript:

document.documentElement.setAttribute('class', 'rotateme'); //Note that this will override the current class

Since you're using a very recent CSS feature, you probably don't need to support older browsers. Therefore, you can also use Element.classList to add a class.

To prevent this from throwing an exception in older browsers, you can check for the existance of it first:

JavaScript:

document.documentElement.classList && document.documentElement.classList.add('rotateme'); //This won't  override the current class

See also: Change an element's class with JavaScript

You use the style attribute on the HTML node.

Something like this will do it:

var htmlNode = document.documentElement;
htmlNode.style.webkitTransform = 'rotate(180deg)';
htmlNode.style.mozTransform = 'rotate(180deg)';

Then, to undo the rotate, set the values to an empty string:

var htmlNode = document.documentElement;
htmlNode.style.webkitTransform = '';
htmlNode.style.mozTransform = '';

Simple

$('#wrap').on('click',function(){
$('html').css('-webkit-transform','rotate(180deg)');
$('html').css('-moz-transform','rotate(180deg)');})
**JQUERY**

$("#imgID").on("click", function(){
    $('html').css({"-webkit-transform": "rotate(180deg)", "moz-transform": "rotate(180deg)"});
});

only js

use user2428118's answer, it's a solid solution.

define a class for this:-

.htmlrotate {
     -webkit-transform: rotate(180deg);
     -moz-transform: rotate(180deg);
}

onclick of the button, run this:-

document.documentElement.classList.add('htmlrotate');
  $('html').bind('click', function () {
                $('html').css({
                    '-webkit-transform': 'rotate(90deg)',
                    '  -moz-transform': 'rotate(90deg)'
                })
            });

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