首页 > 解决方案 > 当鼠标悬停在任何按钮上时执行一个函数

问题描述

所以我有一个页面,我用div. 光标只是页面的一部分,我可以使用CSS. 我想要实现的主要目标是当我将鼠标悬停在任何按钮上时使这个光标改变大小。我无法让它工作......

光标定位由 JQuery 脚本处理,但原版的似乎不想和我一起工作......我无法修复错误......

// Jquery code that moves the cursor (div element)
$(document).on('mousemove', function(e){
	$('#cursor').css({
		left:	e.pageX - 7,
		top:	e.pageY - 7
	});
});

// Function to be executed when mouse is over a button
document.querySelectorAll('button').addEventListener("mouseover", cursorHovering);

function cursorHovering() {
	document.getElementById('object').style = "transform: scale(2);";
}
body {
  height: 300px;
  width: 300px;
  background-color: #ccc;
}

*, body { cursor: none !important; }
#cursor {
    position: fixed;
    z-index: 20000;
    height: 15px;
    width: 15px;
    background-color: #ffffff;
    mix-blend-mode: difference;
    border-radius: 50%;
    opacity: 0;
    transition: 0.3s;
    transition-property: transform, opacity;
    pointer-events: none;
}
body:hover #cursor {
    opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <div id="cursor"></div>
  <button class="button1">Hover over me (1)</button>
  <button class="button2">Hover over me (2)</button>
  <button class="button3">Hover over me (3)</button>
</body>

标签: javascriptjqueryhtmlcss

解决方案


你的意思是这样的?

// Jquery code that moves the cursor (div element)
var c = document.getElementById('cursor');
document.addEventListener('mousemove', (e) => { 
  c.style.left = e.pageX - 7 + 'px';
  c.style.top = e.pageY - 7 + 'px';
});

// Function to be executed when mouse is over a button
document
  .querySelectorAll('button')
  .forEach(b => {
     b.addEventListener("mouseover", () => c.style.transform='scale(2)');
     b.addEventListener("mouseout", () => c.style.transform='scale(1)');
  });
body {
  height: 300px;
  width: 300px;
  background-color: #ccc;
}

*, body { cursor: none !important; }
#cursor {
    position: fixed;
    z-index: 20000;
    height: 15px;
    width: 15px;
    background-color: #ffffff;
    mix-blend-mode: difference;
    border-radius: 50%;
    opacity: 0;
    transition: 0.3s;
    transition-property: transform, opacity;
    pointer-events: none;
}
body:hover #cursor {
    opacity: 1;
}
  
<body>
  <div id="cursor"></div>
  <button class="button1">Hover over me (1)</button>
  <button class="button2">Hover over me (2)</button>
  <button class="button3">Hover over me (3)</button>
</body>


推荐阅读