如何使按钮对文本区域的值做出反应。 Javascript

How to make a button react on the value of a textarea. Javascript

我试图让按钮对文本区域的值做出反应。 btn 代表按钮,txt 代表文本区域,box 是我要操作的 div 元素。

let btn = document.getElementById("funbtn");
let txt = document.getElementById("funtxt");
let box = document.getElementById("funobject");

function answer() {
    if (txt.value === "rotate") {
        let rotate-deg = prompt("How many degrees do you wanna rotate?");
        box.setAttribute("style", "transition: 1000ms ease-in;";
        box.setAttribute("style", "transform: rotate("rotate-deg"deg);";

    }
}


btn.onclick = answer()

您的代码中有一些小错误。

  1. rotate-deg 不是 javascript.
  2. 中变量的有效语法
  3. 您应该将样式合并为一个 .setAttribute-调用或使用 .style-属性。
  4. 在样式中使用 javascript-variables 时有些引号是错误的。支架也没有正确关闭。

这是更正后的版本:

const btn = document.getElementById("funbtn");
const txt = document.getElementById("funtxt");
const box = document.getElementById("funobject");

function answer() {
  if (txt.value === "rotate") {
    let rotateAngle = prompt("How many degrees do you wanna rotate?");
    box.setAttribute("style", "transition: 1000ms ease-in; transform: rotate(" + rotateAngle + "deg);");
  }
}
btn.addEventListener("click", answer);
#funobject {
  width: 80px;
  height: 40px;
  margin-top: 40px;
  background-color: #f00;
}
<input tape="text" id="funtxt">
<button id="funbtn">Action</button>
<div id="funobject"></div>

这与 jquery!

var btn= $("#funbtn");
var txt = $("#funtxt");
var obj = $("#funobject")
btn.on('click',function(){
const val = $.trim(txt.val());
if(val==="rotate"){
obj.css("transform","rotate(180deg)")
}
});
#funobject{
  width:100px;
  height:100px;
  background-color:red;
  transition: all 5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="funtxt">
  
</textarea>
<button id="funbtn">
submit
</button>
<div id="funobject">

</div>

我找到了!

出于某种原因,它必须是 div 元素,而不是在按钮上添加事件侦听器。