变换正是你告诉它的.
它从359deg开始并达到1deg.你希望’翻转’360deg回到1deg,真的是361deg.变换转换的工作方式是在值之间进行插值.
您的问题的解决方案是创建一个包含旋转度的计数器变量:
var rot = 0; // lets start at zero,you can apply whatever later
要应用旋转,请更改值:
rot = 359;
// note the extra brackets to ensure the expression is evaluated before
// the string is assigned this is require in some browsers
element.style.transform = ("rotate( " + rot + "deg )");
所以如果你这样做:
rot = 1;
element.style.transform = ("rotate( " + rot + "deg )");
它回去了.因此,无论经过多少次旋转,您都需要查看它是否接近360或0.您可以通过检查element.style.transform的值来完成此操作,该值只是当前的腐烂值,然后与新的腐烂值进行比较.但是,您需要根据可能存在的旋转次数来执行此操作,因此:
var apparentRot = rot % 360;
现在无论它有多少次旋转,你知道它周围有多远,负值等于值360:
if ( apparentRot < 0 ) { apparentRot += 360; }
现在你已经规范化了任何负值,并且可以询问是否需要正旋转(通过360deg)或负值.由于您似乎将新的旋转值设置为0-360deg,这可以简化您的问题.您可以询问新旋转360是否比新旋转本身更接近旧值:
var aR,// what the current rotation appears to be (apparentRot shortened)
nR,// the new rotation desired (newRot)
rot; // what the current rotation is and thus the 'counter'
// there are two interesting events where you have to rotate through 0/360
// the first is when the original rotation is less than 180 and the new one
// is greater than 180deg larger,then we go through the apparent 0 to 359...
if ( aR < 180 && (nR > (aR + 180)) ) {
// rotate back
rot -= 360;
}
// the second case is when the original rotation is over 180deg and the new
// rotation is less than 180deg smaller
if ( aR >= 180 && (nR <= (aR - 180)) ) {
// rotate forward
rot += 360;
}
除此之外,只需将新旋转的值添加到rot即可:
rot += (nR - aR); // if the apparent rotation is bigger,then the difference is
// 'negatively' added to the counter,so the counter is
// correctly kept,same for nR being larger,the difference is
// added to the counter
清理一下:
var el,rot;
function rotateThis(element,nR) {
var aR;
rot = rot || 0; // if rot undefined or 0,make 0,else rot
aR = rot % 360;
if ( aR < 0 ) { aR += 360; }
if ( aR < 180 && (nR > (aR + 180)) ) { rot -= 360; }
if ( aR >= 180 && (nR <= (aR - 180)) ) { rot += 360; }
rot += (nR - aR);
element.style.transform = ("rotate( " + rot + "deg )");
}
// this is how to intialize and apply 0
el = document.getElementById("elementYouWantToUse");
rotateThis(el,0);
// now call function
rotateThis(el,359);
rotateThis(el,1);
计数器可以是正数或负数,无关紧要,只需使用0-359之间的值进行新的旋转.