使用javascript旋转

Rotate using javascript

本文关键字:旋转 javascript 使用      更新时间:2023-09-26

我想旋转一个div。经过大量的研究,没有javascript旋转一个div不使用css变换,除非使用jquery库。问题是我想做一个小的旋转,并为它添加库不是我的选项。css变换不工作在IE。

在这个例子中,使用javascript来计时分钟、小时和秒。

谁能帮助我得到一个div在IE7上旋转,以上使用javascript本身没有任何额外的库?

这有点晚了,但是我已经写了一些代码来做这个。

http://jsfiddle.net/rlemon/73DzT/

Object.prototype.rotate = function(d) {
    var s = "rotate(" + d + "deg)";
    if (this.style) { // regular DOM Object
        this.style.MozTransform = s
        this.style.WebkitTransform = s;
        this.style.OTransform = s;
        this.style.transform = s;
    } else if (this.css) { // JQuery Object
        this.css("-moz-transform", s);
        this.css("-webkit-transform", s);
        this.css("-o-transform", s);
        this.css("transform", s);
    }
    this.setAttribute("rotation", d);
}

可以用于普通对象或JQuery对象。并存储一个名为"rotation"的属性给你它当前的旋转值。你可以尝试一下,看看你能得到什么。

不使用javascript和jQuery也可以使用原始CSS:

$('#idElement').css({
    /*modern browsers*/
     '-moz-transform':'rotate(88deg)',
     '-webkit-transform':'rotate(88deg)',
     '-o-transform':'rotate(88deg)',
     '-ms-transform':'rotate(88deg)'
     /*IE:*/
     filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476), /* IE6,IE7 */
     -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476)"; /* IE8 */
});

你可以使用简单的javascript改变元素的属性,例如:

document.getElementById("idElement").setAttribute("-moz-transform", "rotate(88deg)");

我不明白为什么不使用jQuery当它更容易的解决方案?

这是我写的快速脚本

$(document).ready(function(){
    $('#element').easyRotate({
       degrees: 45
    });
});

对于javascript,你需要制作div的图片,然后在div内旋转这些图片。我做了一个简单的例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
    <title></title>
</head>
<body>
    <div id="div1">
        <img name="img1" src="myimage1.jpg" id="img1">
        <br>
        <br>
        <input type="button" value="Rotate this image" onclick="rotate()">
    </div><script type="text/javascript">
var tally = 0;
    function rotate() {
    if (tally == 0) {
    document.images["img1"].src= "myimage2.jpg";
    tally = 1;
    return true;
    }
    else {
    document.images["img1"].src= "myimage1.jpg";
    tally = 0;
    return true;
    }
    }
    </script>
</body>
</html>