Два обработчика событий (click и mousemove) одновременно на одном элементе
Я создаю своего рода слайдер, который при нажатии на определенную точку в окне растягивает ширину элемента до этой точки. Я также хотел бы добавить обработчик события перетаскивания, и я прочитал о том, что mousedown и mousemove и mouseup - это три обработчика, которые необходимо объединить. Этот код работает довольно хорошо, но мне интересно, есть ли лучший способ объединить эти обработчики, потому что в данный момент я повторяю код, который я не уверен, что это необходимо. Я совершенно новичок в JavaScript и JQuery. Спасибо за помощь
function reposition_bar(mouse_touch_position){
document.onclick = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
document.onmousemove = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
this.onmouseup = function() {
document.onmousemove = null;
}
}
и вот где я создаю прослушиватель событий.
$(timer_area).on("mousedown", reposition_bar);
мой HTML:
<div id="timer_area0" class="timer_area">
<div id="timer_bar_outer0" class="timer_bar_outer"></div>
<div id="timer_bar0" class="timer_bar"></div>
</div>
и мой css:
.timer_area{
position: relative;
width: 100%;
margin: 20px auto 10px auto;
height: 20px;
backgroud: #fff;
}
.timer_bar{
z-index: -1;
display: block;
width: 3%;
height: 8px;
border-radius: 4px;
clear: both;
position: absolute;
margin-top: 6px;
box-shadow: inset 0px 1px 0px 0px rgba(250,250,250,0.5),
0px 0px 3px 2px rgba(250,250,250,1);
background-color: #fff;
}
.timer_bar_outer{
padding: 0px 3% 0px 3%;
width: 100%; /*this should be same number as 100/windowduration*/
height: 20px;
display: block;
z-index: -2;
position: absolute;
background-color: rgb(0,0,0);
margin-left: -3%;
border-radius: 10px;
box-shadow: 0px 1px 0px 0px rgba(250,250,250,0.1),
inset 0px 1px 2px rgba(0, 0, 0, 0.5);
box-sizing: content-box;
}
.timer_bar.on{
background-color: blue;
box-shadow: inset 0px 1px 0px 0px rgba(250,250,250,0.5),
0px 0px 3px 2px rgba(5,242,255,1);
}
Изменить после комментария @tlindell:
Спасибо за ваш комментарий. Я попробовал ползунки диапазона, но не смог придать им стиль css так, как мне хотелось после долгих исследований. (т.е. мой вертикальный слайдер работал идеально, пока я не наложил на него тень от коробки, и он больше не работал вертикально)... Я доволен своим слайдером. Просто мне было интересно, если бы я мог написать метод reposition_bar лучше, потому что, как я сделал это выше, этот код:
document.onclick = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
точно так же, как это принять, они разные обработчики событий, например, onmousemove и onclick:
document.onmousemove = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
так что я могу объединить их таким образом, например,
document.onmousemove || document.onclick = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
Спасибо за ваше редактирование @tlindell. Это что-то вроде того, что я хотел бы, но я попробовал следующее, которое действительно не дает желаемого эффекта. Это не регистрация события mouseup.
function reposition_bar(mouse_touch_position){
document.onmousemove = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
this.onmouseup = function() {
document.onmousemove = null;
}
}
$(timer_area).on("mousedown click", reposition_bar);
Я хотел бы, чтобы функция вызывалась с помощью onmousedown, а затем внутри функции, которую я хотел бы обрабатывать события onmousemove и onclick. могу ли я сделать что-то подобное в функции reposition_bar:
function reposition_bar(mouse_touch_position){
document.on("mousemove click") = function(mouse_touch_position){
var timer_bar_position = $(timer_bar);
timer_bar_offset = timer_bar_position.offset();
var total_width_timer = $("#timer_bar_outer0").width();
var new_width_timer = (((mouse_touch_position.pageX - timer_bar_offset.left)/total_width_timer) * 100); /*converting to percantages because the width of the timer is in percentages in css*/
player.currentTime = (window.duration)*(new_width_timer/100);
}
this.onmouseup = function() {
document.onmousemove = null;
}
}
$(timer_area).on("mousedown", reposition_bar);
Это не работает вообще, хотя, я думаю, синтаксис в этой строке неправильный:
document.on("mousemove click") = function(mouse_touch_position){
}
Еще раз спасибо. Я новичок в этом:)
Спасибо @tlindell за ответ. Это то, что я сделал в конце. (см. раздел window.onload для изменений)
<script>
var player;
var intv;
var duration;
var song_id;
var button;
//init
window.onload = function(){
player = document.getElementById('audio_player');
$('#volume_control_area').on('mousedown mouseup mouseleave click', function(e){
if(e.type === 'mousedown'){
$(this).bind('mousemove', reposition);
}
else if((e.type === 'mouseup') || (e.type === 'mouseleave')) {
$(this).unbind('mousemove', reposition);
}else if(e.type === 'click'){
$(this).bind('click', reposition);
}
});
}
function reposition(mouse_volume_position){
var volume_knob_position = $(".volume_control_knob");
volume_area_offset = $('#volume_control_area').offset();
var total_height_volume = $('#volume_control_area').height();
console.log(total_height_volume);
var new_height_volume = ((volume_area_offset.top + total_height_volume)- mouse_volume_position.pageY); /*converting to percantages because the width of the timer is in percentages in css*/
if(new_height_volume > 8 && new_height_volume <= 100){
console.log(new_height_volume);
player.volume = new_height_volume/100;
$(".volume_control_knob").css({
'height' : new_height_volume + '%'
});
}
}
</script>
1 ответ
Добро пожаловать JQuery UI!
Вы можете изменить размер div здесь:
и получите ползунки диапазона здесь:
РЕДАКТИРОВАТЬ
абсолютно! вот способ сделать это.
$('#element').on('keyup keypress blur change', function() {
...
});
Или просто передайте функцию в качестве параметра обычным функциям события:
var myFunction = function() {
...
}
$('#element')
.keyup(myFunction)
.keypress(myFunction)
.blur(myFunction)
.change(myFunction)
JQuery несколько событий для запуска одной и той же функции
ОБНОВИТЬ:
<script>
let player;
let intv;
let duration;
let song_id;
let button;
//init
window.onload = function(){
player = document.getElementById('audio_player');
$('#volume_control_area').on('mousedown mouseup', function(e){
if(e.type === 'mousedown'){
$(this).bind('mousemove', reposition);
}
else if(e.type === 'mouseup'){
$(this).unbind('mousemove', reposition);
}
})
}
function reposition(mouse_volume_position){
let volume_knob_position = $(".volume_control_knob");
let volume_area_offset = $('#volume_control_area').offset();
let total_height_volume = $(volume_control_area).height();
let new_height_volume = ((volume_area_offset.top + total_height_volume)- mouse_volume_position.pageY); /*converting to percantages because the width of the timer is in percentages in css*/
if(new_height_volume > 8 && new_height_volume <= 100){
console.log(new_height_volume);
player.volume = new_height_volume/100;
$(".volume_control_knob").css({
'height' : new_height_volume + '%'
});
}
}
</script>