short question, how to check if image already rotate with Jquery like :
if($("image").css({transform}) == "rotate(-180deg)"){ do something}
CodePudding user response:
Best Practice is to make a class with the css condition you want:
.rotated {
transform: rotate(-180deg);
}
and then check if the img
hasClass:
if($("img").hasClass("rotated")){
alert('true...')
} else {
alert('false...')
}
You may also need .addClass()
& .removeClass()
& .toggleClass()
.
take a look @ Jquery API Documentation
CodePudding user response:
You'd think it'd be that easy - but because it's a transform property you're not going to get a simple response like that. The solution is raw javascript - the only place jQuery can participate is in getting the element. As this article shows, the way to calculate the current angle of the element ...
function getCurrentAngle(el) {
let st = window.getComputedStyle(el, null);
let tr = st.getPropertyValue("-webkit-transform") ||
st.getPropertyValue("-moz-transform") ||
st.getPropertyValue("-ms-transform") ||
st.getPropertyValue("-o-transform") ||
st.getPropertyValue("transform") ||
"Either no transform set, or browser doesn't do getComputedStyle";
// console.log('this returns a matrix transform', tr);
// Here is the way we can turn that into what we're looking for
// rotate(Xdeg) = matrix(cos(X), sin(X), -sin(X), cos(X), 0, 0);
let values = tr.split('(')[1].split(')')[0].split(',');
let a = values[0]; // 0.866025
let b = values[1]; // 0.5
let c = values[2]; // -0.5
let d = values[3]; // 0.866025
let angle = Math.round(Math.asin(b) * (180 / Math.PI));
return angle;
}
window.addEventListener('DOMContentLoaded', () => {
let el = document.getElementById("i-am-rotated");
console.log(getCurrentAngle(el));
setTimeout(() => {
el.style.transform = "rotate(49deg)";
}, 500)
setTimeout(() => {
console.log(getCurrentAngle(el));
}, 1000)
})
.container {
padding: 50px;
background: #f0f0f0;
text-align: center;
}
#i-am-rotated {
display: inline-block;
-webkit-transform: rotate(30deg);
-moz-transform: rotate(30deg);
-ms-transform: rotate(30deg);
-o-transform: rotate(30deg);
transform: rotate(30deg);
transition: transform .5s;
}
<div class='container'>
<div id='i-am-rotated'>I am rotated</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>