Implement rotation/rotation of objects using form input and sliders
P粉007288593
2023-08-16 16:16:28
<p>I have an object called #person and I need to rotate it from -180 degrees to 180 degrees with the input of a slider. I've synchronized the slider with the input box to display the current angle value and tried writing a function but it didn't work. I'm trying to use style.transform. Having used Bootstrap and jQueryUI in my project, it would also be helpful if I could use these two frameworks instead of standard JavaScript to solve the problem. </p>
<pre class="brush:php;toolbar:false;">HTML
<label for="angleSlider" class="form-label">rotation angle</label>
<form>
<input type="range" class="form-range w-75" id="thetaRange" min="-180" max="180" value="0"
oninput="this.form.thetaInput.value=this.value" />
<input type="number" id="thetaInput" min="-180" max="180" value="0"
oninput="this.form.thetaRange.value=this.value" />
</form></pre>
<pre class="brush:php;toolbar:false;">Javascript
function rotatePerson() {
const person = document.getElementById("person");
var angle = document.getElementById("thetaRange");
person.style.transform = "rotate(angle deg)"
}</pre></p>
The code snippet you provided is almost correct, but there are some issues in the last line of JavaScript code. Here is the corrected version and its explanation:
function rotatePerson() { const person = document.getElementById("person"); var angle = document.getElementById("thetaRange").value; // 获取角度的值 person.style.transform = "rotate(" + angle + "deg)"; // 将角度变量连接到transform属性中 }explain:
1.
rotatePersonThe function usesgetElementByIdto select the element with the ID "person" and assigns it to the variableperson.2. Next, it gets the value of the angle from the element with ID "thetaRange" using
getElementByIdand accessing thevalueproperty. This value represents the currently selected angle on the slider.3. Finally, the code sets the
style.transformattribute of thepersonelement torotate(" angle "deg). This will dynamically apply rotation to thepersonelement, using the degree valueangleobtained from the slider.By calling the
rotatePersonfunction when the slider value changes, the person element will be rotated according to the selected angle.