search

Home  >  Q&A  >  body text

Implement rotation/rotation of objects using form input and sliders

<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>
P粉007288593P粉007288593467 days ago505

reply all(1)I'll reply

  • P粉882357979

    P粉8823579792023-08-17 14:01:06

    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. rotatePerson The function uses getElementById to select the element with the ID "person" and assigns it to the variable person.

    2. Next, it gets the value of the angle from the element with ID "thetaRange" using getElementById and accessing the value property. This value represents the currently selected angle on the slider.

    3. Finally, the code sets the style.transform attribute of the person element to rotate(" angle "deg). This will dynamically apply rotation to the person element, using the degree value angle obtained from the slider.

    By calling the rotatePerson function when the slider value changes, the person element will be rotated according to the selected angle.

    reply
    0
  • Cancelreply