以不同颜色读取和显示滑块值的函数

我在尝试创建一个函数来读取从滑块获得的值然后根据其值以不同颜色显示它时遇到了很多麻烦。


这是我到目前为止的代码:


function slider() {

  document.getElementById("formControlRange").oninput = function() {

    percentagem()

  };

}


function percentagem() {

  var val = document.getElementById("formControlRange").value document.getElementById('formOutput').innerHTML = val

  if ($("#formControlRange").val() >=

    50) {

    $("#formOutput").addClass("alert-sucess");

  } else {

    $("#formOutput").addClass("alert-danger");

  }

}

console.log(val)

}

<div class="form-row">

  <div class="form-group col-md-6">

    <label for="formControlRange">Com que percentagem recomendaria o Bootstrap a terceiros?</label>

    <input type="range" class="form-control-range" id="formControlRange" onchange="slider()" min="0" max="100">

  </div>

  <div class="form-group col-md-6">

    <h1><output id="formOutput" class=""></output></h1>

  </div>

</div>


桃花长相依
浏览 156回答 1
1回答

Cats萌萌

如果您希望“alert-success”和“alert-danger”起作用,则必须将“alert”类添加到您的元素中。并且每次值更改时都必须重置类。另外要小心分号和花括号。function slider() {&nbsp; document.getElementById("formControlRange").oninput = function() {&nbsp; &nbsp; percentagem()&nbsp; };}function percentagem() {&nbsp; var val = document.getElementById("formControlRange").value;&nbsp; document.getElementById('formOutput').innerHTML = val;&nbsp; $("#formOutput").removeClass("alert-sucess alert-danger");&nbsp; if ($("#formControlRange").val() >= 50) {&nbsp; &nbsp; $("#formOutput").addClass("alert-success");&nbsp; } else {&nbsp; &nbsp; $("#formOutput").addClass("alert-danger");&nbsp; }}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"><div class="form-row">&nbsp; <div class="form-group col-md-6">&nbsp; &nbsp; <label for="formControlRange">Com que percentagem recomendaria o Bootstrap a terceiros?</label>&nbsp; &nbsp; <input type="range" class="form-control-range" id="formControlRange" onchange="slider()" min="0" max="100">&nbsp; </div>&nbsp; <div class="form-group col-md-6">&nbsp; &nbsp; <h1><output id="formOutput" class="alert"></output></h1>&nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript