Как отключить мышиную прокрутку на входном диапазоне - PullRequest
0 голосов
/ 29 сентября 2019

У меня есть диапазон ввода, и я хочу выбрать его значения только тогда, когда я нажимаю на него.Проблема в том, что если вы щелкнете по диапазону, оставьте мышь в верхней части диапазона и прокрутите колесико мыши, это изменит значение диапазона.Я уже пробовал CSS и JQuery, но я не могу понять, как это сделать.Я также хочу определить значение по умолчанию для запуска прокрутки, но я не управляю как.

Вот ссылка fiddle .

    <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;
    }

Большое спасибо!

1 Ответ

1 голос
/ 29 сентября 2019

Вам нужно будет использовать «прослушиватели событий» для прослушивания изменений / взаимодействий с вашей страницей (прокрутка, ввод пользователя и т. Д.).В приведенном ниже примере я использовал события 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);

¹ https://api.jquery.com/on/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...