jquery - 如何在输入范围内禁用鼠标滚动
问题描述
我有一个范围输入,我想在单击它时选择它的值。问题是,如果您单击范围,将鼠标留在范围顶部并滚动鼠标滚轮,它将更改范围的值。我已经尝试过css和jquery,但我不知道该怎么做。我还想定义一个默认值来启动滚动,但我不管理如何。
这是小提琴链接。
<input type="range" id="range_year_donut" min="" max="" value="" onchange="slideyear()">
<span id="chosen_year"></span>
var range_year = d3.select("#range_year_donut");
d3.csv("http://raw.githubusercontent.com/cvrnogueira/CODWorkData/master/database/final_data_set.csv").then(function(data){
let max = d3.max(data, function(d) {return +d.year});
let min = d3.min(data, function(d) {return +d.year});
range_year.attr("min", min)
.attr("max", max)
.attr("value", max);
});
function slideyear(){
let year = range_year.node().value;
}
非常感谢!
解决方案
您需要使用“事件侦听器”来侦听与页面的更改/交互(滚动、用户输入等)。在下面的示例中,我将“mouseover”和“wheel”事件与 jQuery 的on
方法¹结合使用(请参阅代码中的注释以获得进一步的解释):
$(function() {
// The slider and <span> label
const
slider = $("#range_year_donut"),
sliderLabel = $("#chosen_year");
// This variable will be whichever element the user has moved their mouse over
let currentElement = null;
// Attach event listeners to the document for "mouseover" and "wheel" events
$(document)
.on("mouseover", function(e) {
// Any time the mouse is moved over an element in the document, set currentElement
currentElement = e.target;
})
.on("wheel", function(e) {
// The "wheel" event is triggered any time the mousewheel is used.
//
// If currentElement is the slider then its "ID" attribute will be the same as
// the "slider" variable defined at the top.
if (currentElement && currentElement.id === slider.attr("id")) {
// Calling preventDefault() will cancel the default behaviour, i.e. scrolling
e.preventDefault();
console.log("current element is slider; preventing scroll");
}
});
// Rather than using the "onchange" HTML attribute, we can also attach an event listener
// to the slider using the "input" event.
slider.on("input", function() {
// The current value
const sliderValue = $(this).val();
// Set the label's text to the value
sliderLabel.text(sliderValue);
})
// For this example, manually trigger the "input" event to update the slider label
slider.trigger("input");
})
<input type="range" id="range_year_donut" min="-10" max="10" value="0" />
<span id="chosen_year"></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
我还想定义一个默认值来启动滚动,但我不管理如何。
您可以设置value
使用 jQuery 的val
方法,例如
slider.val(5);
推荐阅读
- html - 如何将按钮放在输入旁边?
- reactjs - React with Redux - 回调函数被意外调用
- reactjs - 在 Gatsby Netlify 启动器中,使用自定义预览组件、不可变 entry.getIn 和 widgetsFor 从列表中返回空对象
- django - 在 Django 中按优先级提供行
- pandas - 如何从标签列表中为熊猫图设置 xticks?
- button - 无法更新按钮显示数据
- javascript - 匹配某个字符后的任何内容
- python - 如何从解析的 HTML 中打印特定元素?
- java - 为列表的每个索引引用相同类的不同类对象
- scheme - 使用列表反转数字的数字