【问题标题】:How to make a button react on the value of a textarea. Javascript如何使按钮对文本区域的值做出反应。 Javascript
【发布时间】:2019-05-22 09:45:07
【问题描述】:

我试图让按钮对 textarea 的值做出反应。 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()

【问题讨论】:

  • rotate-deg 语法无效,请使用rotateDeg
  • 更正错别字:"transform: rotate("+rotate-deg+"deg);
  • @jeff 即使rotate-deg 不正确
  • oooppps - 修正:将 rotate-deg 更改为 rotateDeg 然后更改:“transform: rotate("+rotateDeg+"deg);

标签: javascript events textarea


【解决方案1】:

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

  1. rotate-deg 不是 javascript 中变量的有效语法。
  2. 您应该将这些样式组合成一个.setAttribute-call 或使用.style-properties。
  3. 在样式中使用 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>

【讨论】:

  • 我尝试对其进行测试,但出现了同样的错误。它不会重新调整变量...当我在控制台中编写完全相同的行时,它可以工作...
【解决方案2】:

这个用 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>

【讨论】:

    【解决方案3】:

    我发现了!

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 2012-10-22
      • 2016-09-05
      相关资源
      最近更新 更多