【发布时间】:2016-08-22 21:30:55
【问题描述】:
我正在尝试使用鼠标滚轮增加/减少输入字段的值。我整理了以下代码。它工作正常,但有一个小问题。
我想要的行为是,一旦我专注于元素,就能够使用鼠标滚轮增加/减少输入值。鼠标不必悬停在元素上。以下代码执行此操作。但是,如果我在悬停输入元素时使用滚轮,则该值会增加/减少 2 而不是 1。
var hoveredInput = null;
$('input[type="number"]').on("focus", function(e) {
hoveredInput = this;
});
$('input[type="number"]').on("blur", function(e) {
hoveredInput = null;
});
$(window).on("wheel", function(e) {
if (hoveredInput) {
if (e.originalEvent.deltaY < 0) {
var currentValue = parseInt(hoveredInput.value, 10);
var newValue = currentValue + 1;
if (newValue > parseInt(hoveredInput.max, 10)) {
newValue = hoveredInput.max;
}
hoveredInput.value = newValue;
} else {
var currentValue = parseInt(hoveredInput.value, 10);
var newValue = currentValue - 1;
if (newValue < parseInt(hoveredInput.min, 10)) {
newValue = hoveredInput.min;
}
hoveredInput.value = newValue;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="0" min="0" max="255" />
经过一些试验,我发现向上和向下箭头键有类似的行为。向上和向下箭头键,在数字输入上,增加/减少值。而且我想,这种行为与我的代码冲突。导致它增加 2,即使代码没有执行两次。
我刚刚意识到这可能是 Chrome 特有的问题。如果您聚焦并悬停元素,Chrome 让您使用鼠标滚轮增加/减少数字输入值。但是,它的工作方式非常奇怪。
如果我只是在空白 HTML 页面中添加 <input type="number" />,则此鼠标滚轮增量不起作用。为了使它工作,我只需添加window.onwheel = function() {};。这没有任何意义。这似乎也适用于JSFiddle 和JSBin,而没有window 上的onwheel 分配。
回到实际问题,我可以禁用元素上的默认鼠标滚轮增量,以便我可以使用自定义的吗?或者我可以使用其他方法吗?
【问题讨论】:
标签: javascript google-chrome input dom-events mousewheel