Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检测鼠标在图像上的位置_Javascript_Jquery - Fatal编程技术网

Javascript 检测鼠标在图像上的位置

Javascript 检测鼠标在图像上的位置,javascript,jquery,Javascript,Jquery,在一张图片(幻灯片)上,我想检测一下courser放在哪一边。e、 g图像的左半边或右半边。我想在用户将鼠标移到图像上时显示箭头(左箭头和右箭头),根据位置,我将显示右箭头或左箭头。我只需要知道如何在图像上检测鼠标移动。谢谢 在img标记或div标记中使用eventonmouseinter和onmouseleave(您可以在幻灯片中从左到右划分两个区域) 例如: <img onmouseenter="showArrow(position)" onmouseleave="hideArrow(

在一张图片(幻灯片)上,我想检测一下courser放在哪一边。e、 g图像的左半边或右半边。我想在用户将鼠标移到图像上时显示箭头(左箭头和右箭头),根据位置,我将显示右箭头或左箭头。我只需要知道如何在图像上检测鼠标移动。谢谢

img
标记或
div
标记中使用event
onmouseinter
onmouseleave
(您可以在幻灯片中从左到右划分两个区域)

例如:

<img onmouseenter="showArrow(position)" onmouseleave="hideArrow(position)" src="">

  • onmouseinter
    当鼠标指针指向图像时
  • onmouseleave
    当鼠标指针离开图像时

这是一些能够检测图像上光标相对位置的代码。您可以根据返回值(而不是console.log)重新调整其用途,以显示/隐藏箭头图标

添加了自动隐藏箭头的
mouseout
侦听器

const img=document.getElementById('imageTest');
常量[imgRects]=img.getClientRects();
//设showLeftArrow=false;
//设showRightArrow=false;
img.addEventListener('mouseover',evt=>{
const distance left=Math.abs(evt.clientX-imgRects.left);
const distance right=Math.abs(evt.clientX-imgRects.right);
如果(距离左<距离右){
//showLeftArrow=true;
//showRightArrow=false;
console.log('left');
}否则{
//showLeftArrow=false;
//showRightArrow=true;
console.log('right');
}
});
/*
img.addEventListener('mouseout',()=>{
showLeftArrow=false;
showRightArrow=false;
})
*/

为什么要使用
JavaScript
,而您可以使用
CSS
实现这一点。谢谢。是否可以使用更简单的方法,例如:$(“.object img”).on(“mousemove”,function(event){var x=event.pageX-this.offsetLeft;if(x<$(this.width()/2)console.log(“left”);else console.log(“right”);};我相信偏移量值将相对于它们的容器,而不是整个页面:()我正在使用jquery。。。嗯,试试你的脚本,我得到了一个未定义的getclientres。我正在将const改为var,因为我正在使用vanilla js:-)如果您能够,我将使用jQuery标记更新您的问题,如果这是您需要的解决方案。至于
getClientRects
问题,这可能有助于:
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'));