Показывать вертикальную линию отслеживания при наведении на несколько элементов - PullRequest
1 голос
/ 27 марта 2019

Я хочу показать вертикальную линию, которая появится, когда мои диаграммы наведены и исчезнут, когда мышь выйдет из элементов диаграммы.Как ни странно, события mouseleave и mouseout, похоже, запускаются, когда мышь не движется или когда она движется вверх и вниз (а не из стороны в сторону), см. Фрагмент кода ниже.Я не хочу, чтобы линия исчезала, когда мышь останавливается, и я хочу, чтобы она отслеживала мышь, куда бы она ни шла.

Я пытался запустить код при наведении курсора, mouseenter и mouseover, но mousemove (см. Код ниже) - единственное событие, которое непрерывно срабатывает при изменении положения курсора.

//$(document).ready(function() {
	function showVerticalLine(e) {
		var topBarHeight = 56;
    var bottomHeight = 100;
		var posX = $(this).offset().left;
		var x = e.pageX;
		var y = $(window).innerHeight();
    
    //Change line so that it appears at the position of the cursor
		$('.verticalTrackerLine').css({
			'opacity': '1',
			'left': x,
			'top': topBarHeight,
			'height': y - topBarHeight - bottomHeight + "px",
			'transition': 'left 0.1s'
		});
    
    //Update string to show when the charts are being hovered over
		$("#testSTRING").html('you are moving/hovering');
	};
	
	function hideVerticalLine(){
    //Hide the line
		$('.verticalTrackerLine').css({
			'opacity': '0'
		});
    
    //Update string to show when the charts are being hovered over
		$("#testSTRING").html('you have left');
	}
  
  $("#chart1").add("#chart2").mousemove(showVerticalLine);
  $("#chart1").add("#chart2").mouseout(hideVerticalLine);
//})
.chart {
  margin-top: 30px;
  width: 100px;
  height: 30px;
  border: 1px solid black;
  background-color: red;
}

.verticalTrackerLine {
  border-left: 2px dashed RGB(68,74,79);
   position: fixed;
   z-index: 1;
   opacity: 0;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<SPAN id="testSTRING"></SPAN>
<SPAN class="verticalTrackerLine"></SPAN>

<DIV id="chart1" class="chart">Chart 1</DIV>
<DIV id="chart2" class="chart">Chart 2</DIV>



</head>

Любая помощь / предложения будут с благодарностью приняты.

Ответы [ 3 ]

2 голосов
/ 27 марта 2019

Ваше предположение верно, когда вы наводите курсор на фактическую линию, которая мешает зависанию над кнопками. Таким образом, просто добавив pointer-events: none; в селектор .verticalTrackerLine, вы исправите это так, что мышь вообще не будет взаимодействовать со строкой.

Я также сделал небольшую очистку JS для вашего кода, ничего особенного. Правило CSS transition: left 0.1s не требует повторного применения при каждом перемещении мыши, так что теперь оно установлено в CSS.

$(function() {
    var topBarHeight = 56;
    var bottomHeight = 100;
    var $line = $('.verticalTrackerLine');
    var $charts = $("#chart1, #chart2");
    var $test = $("#testSTRING");

    function showVerticalLine(e) {
      var posX = $(this).offset().left;
      var x = e.pageX;
      var y = $(window).innerHeight();

      //Change line so that it appears at the position of the cursor
      $line.css({
        'opacity': 1,
        'left': x,
        'top': topBarHeight,
        'height': y - topBarHeight - bottomHeight + "px"
      });

      //Update string to show when the charts are being hovered over
      $test.html('you are moving/hovering');
    };

    function hideVerticalLine() {
      //Hide the line
      $line.css('opacity', 0);

      //Update string to show when the charts are being hovered over
      $test.html('you have left');
    }

    $charts
      .mousemove(showVerticalLine)
      .mouseout(hideVerticalLine);
});
.chart {
  margin-top: 30px;
  width: 100px;
  height: 30px;
  border: 1px solid black;
  background-color: red;
}

.verticalTrackerLine {
  border-left: 2px dashed RGB(68, 74, 79);
  position: fixed;
  z-index: 1;
  opacity: 0;
  transition: left 0.1s;/* <------ this was moved from JS */
  pointer-events: none; /* <------ this was added */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<output id="testSTRING">nothing has happened yet...</output>
<span class="verticalTrackerLine"></span>

<div id="chart1" class="chart">Chart 1</div>
<div id="chart2" class="chart">Chart 2</div>
1 голос
/ 27 марта 2019

Добавить pointer-events: none; к .verticalTrackerLine

//$(document).ready(function() {
	function showVerticalLine(e) {
		var topBarHeight = 56;
    var bottomHeight = 100;
		var posX = $(this).offset().left;
		var x = e.pageX;
		var y = $(window).innerHeight();
    
    //Change line so that it appears at the position of the cursor
		$('.verticalTrackerLine').css({
			'opacity': '1',
			'left': x,
			'top': topBarHeight,
			'height': y - topBarHeight - bottomHeight + "px",
			'transition': 'left 0.1s'
		});
    
    //Update string to show when the charts are being hovered over
		$("#testSTRING").html('you are moving/hovering');
	};
	
	function hideVerticalLine(){
    //Hide the line
		$('.verticalTrackerLine').css({
			'opacity': '0'
		});
    
    //Update string to show when the charts are being hovered over
		$("#testSTRING").html('you have left');
	}
  
  $("#chart1").add("#chart2").mousemove(showVerticalLine);
  $("#chart1").add("#chart2").mouseout(hideVerticalLine);
//})
.chart {
  margin-top: 30px;
  width: 100px;
  height: 30px;
  border: 1px solid black;
  background-color: red;
}

.verticalTrackerLine {
  border-left: 2px dashed RGB(68,74,79);
   position: fixed;
   z-index: 1;
   opacity: 0;
   pointer-events: none;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<SPAN id="testSTRING"></SPAN>
<SPAN class="verticalTrackerLine"></SPAN>

<DIV id="chart1" class="chart">Chart 1</DIV>
<DIV id="chart2" class="chart">Chart 2</DIV>



</head>
1 голос
/ 27 марта 2019

Вы можете упростить это далее:

  • переместите линию отслеживания в :after псевдоэлемент внутри каждого chart элемента и позицию это абсолютно в пределах chart
  • поместите его на 10 пикселей больше сверху и снизу, используя:

    top: -10px;
    bottom: -10px;
    
  • установите opacity: 0 на линию отслеживания и на :hover установите ее на единицу - теперь у вас будет линия при наведении - см. Демонстрацию ниже:

.chart {
  margin-top: 30px;
  width: 100px;
  height: 30px;
  border: 1px solid black;
  background-color: red;
  position: relative;
  box-sizing: border-box;
}

.chart:after {
  content: '';
  border-left: 2px dashed rgb(68, 74, 79);
  position: absolute;
  z-index: 1;
  opacity: 0;
  top: -10px;
  bottom: -10px;
}

.chart:hover:after {
  opacity: 1;
}
<div id="chart1" class="chart">Chart 1</div>
<div id="chart2" class="chart">Chart 2</div>

Теперь идёт часть javascript - мы можем изменить свойство left, чтобы показывать линию, перемещающуюся с помощью мыши:

  • сначала добавьте CSS-переменную (скажем, --left), которую можно настроить в JS

  • теперь в mousemove слушателе вы можете использовать e.pageX - this.offsetLeft, чтобы получить относительное положение (left значение) мыши внутри блока.

  • обновить CSS-переменную --left, используя document.documentElement.style.setProperty('--left', ...

  • Обратите внимание, что я установил максимальное значение , чтобы значение left было безопасным для this.offsetWidth - 2.

См. Демо ниже:

$(".chart").mousemove(function (e) {
  document.documentElement.style.setProperty('--left', Math.min(e.pageX - this.offsetLeft, this.offsetWidth - 2) + 'px');
});
:root {
  --left: 0;
}

.chart {
  margin-top: 30px;
  width: 100px;
  height: 30px;
  border: 1px solid black;
  background-color: red;
  position: relative;
  box-sizing: border-box;
}

.chart:after {
  content: '';
  border-left: 2px dashed rgb(68, 74, 79);
  position: absolute;
  z-index: 1;
  opacity: 0;
  top: -10px;
  bottom: -10px;
  left: var(--left);
}

.chart:hover:after {
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart1" class="chart">Chart 1</div>
<div id="chart2" class="chart">Chart 2</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...