简体   繁体   English

检测鼠标在图像上的位置

[英]detect mouse position over image

On an image (slideshow) I would like to detect on which side the courser is placed.在图像(幻灯片)上,我想检测路线放置在哪一侧。 eg the left-half side of the image or the right-half side of the image.例如图像的左半边或图像的右半边。 I would like to show an arrow (left and right) when the user is mouseover the image and depending on the location I will show the right or the left arrow.当用户将鼠标悬停在图像上时,我想显示一个箭头(向左和向右),并且根据位置我将显示向右或向左箭头。 I just need to know how to achieve the detection of the mousemove over the image.我只需要知道如何实现对图像上鼠标移动的检测。 Thanks!谢谢!

Use event onmouseenter and onmouseleave in img tag or div tag (you can divide two areas left-right in slideshow)img标签或div标签中使用onmouseenteronmouseleave事件(可以在幻灯片中将左右两个区域分开)

For example:例如:

<img onmouseenter="showArrow(position)" onmouseleave="hideArrow(position)" src="">
  • onmouseenter when the mouse pointer onto an image当鼠标指针移到图像上时onmouseenter
  • onmouseleave when the mouse pointer out of an image当鼠标指针离开图像时onmouseleave
var imageElement = document.querySelector('.imageElement');
var arrowsElemennt = document.querySelector('.arrowsElement');

var setStatusForArrows = function(status){return function(){arrowsElement.style.display = status}};

imageElement.addEventListener('mouseover',setStatusForArrows('block'));
imageElement.addEventListener('mouseout', setStatusForArrows('none'));

This is some code that is able to detect the relative cursor position over an image.这是一些能够检测图像上的相对光标位置的代码。 You could repurpose this to show/hide your arrow icons based on its return value (instead of the console.log).您可以根据其返回值(而不是 console.log)重新调整它的用途,以显示/隐藏箭头图标。

Added mouseout listener for auto-hiding arrows.为自动隐藏箭头添加了mouseout侦听器。

 const img = document.getElementById('imageTest'); const [imgRects] = img.getClientRects(); // let showLeftArrow = false; // let showRightArrow = false; img.addEventListener('mouseover', evt => { const distanceLeft = Math.abs(evt.clientX - imgRects.left); const distanceRight = Math.abs(evt.clientX - imgRects.right); if (distanceLeft < distanceRight) { // showLeftArrow = true; // showRightArrow = false; console.log('left'); } else { // showLeftArrow = false; // showRightArrow = true; console.log('right'); } }); /* img.addEventListener('mouseout', () => { showLeftArrow = false; showRightArrow = false; }) */
 <img id="imageTest" src="https://vuejs.org/images/logo.png" style="height:30px;width:30px" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM