点击加减按钮jquery将输入值增加或减少0.25

nhjlsmyf  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(115)

这是参考网站https://ekaya.in/products/handwoven-wine-silk-fabric-4324
这里的数量值增加了.25每次我们点击“+”图标,我试图实现同样的事情,但我无法显示“+”和“-”图标,这里是我的代码<input type="number" placeholder="1.0" step="0.5" min="0" max="10">有人可以请帮助

gpnt7bae

gpnt7bae1#

您可以使用stepUp()增加值,stepDown()减少值,如下所示:

const inputEl = document.getElementById("qntyInput");

//attach click event handler to the parent
document.querySelector(".qnty-control").addEventListener("click", (event) => {
  //check if minus button is clicked
  if (event.target.classList.contains("minus")) {
    //decrease
    inputEl.stepDown();
  } else if (event.target.classList.contains("plus")) {
    //increase if plus button is clicked
    inputEl.stepUp();
  }
});

inputEl.addEventListener("input", () => {
  //format the input to 2 decimal places
  inputEl.value = parseFloat(inputEl.value).toFixed(2);
});
.qnty-control span {
  display: inline-block;
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  cursor: pointer;
  border: 1px solid #ccc;
  user-select: none;
  font-style: bold;
}
<div class="qnty-control">
  <span class="minus">-</span>
  <input type="number" id="qntyInput" placeholder="1.0" step="0.25" min="0" max="10">
  <span class="plus">+</span>
</div>

使用jQuery:

$(document).ready(function() {
  //event handler for "+" button
  $(".plus").on("click", function() {
    const input = $("#qntyInput")[0];
    input.stepUp();
  });

  //event handler for "-" button
  $(".minus").on("click", function() {
    const input = $("#qntyInput")[0];
    input.stepDown();
  });

  //format the input value to 2 decimal places
  $("#qntyInput").on("input", function() {
    const value = parseFloat($(this).val());
    $(this).val(value.toFixed(2));
  });
});
.qnty-control span {
  display: inline-block;
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  cursor: pointer;
  border: 1px solid #ccc;
  user-select: none;
  font-style: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="qnty-control">
  <span class="minus">-</span>
  <input type="number" id="qntyInput" placeholder="1.0" step="0.25" min="0" max="10">
  <span class="plus">+</span>
</div>

相关问题