简体   繁体   English

使用鼠标位置更改div样式的Javascript函数

[英]Javascript function that uses mouse position to change div style

I'm working with a div in an HTML page that I need to switch the css style of as I move the mouse throughout the page. 我正在HTML页面中使用div,因此需要在将鼠标移到整个页面时切换css样式。

Is there any function I can use to constantly track the mouse location? 我可以使用任何功能来不断跟踪鼠标位置吗? I need to switch the particular div's css style to a different css style as soon as the mouse is at least 30 px from the top of the page. 一旦鼠标距页面顶部至少30 px,我需要将特定div的CSS样式切换为其他CSS样式。 While the mouse cursor is within 30px distance from the top of the page, I want the div to have a particular style. 虽然鼠标光标在距页面顶部30px的距离内,但我希望div具有特定的样式。 If it is farther than 30 px from the top of the page, I want it to switch styles. 如果距离页面顶部的距离超过30像素,我希望它切换样式。

assume i have 2 different styles in my css I can switch back and forth. 假设我在CSS中有2种不同的样式,可以来回切换。

Use a mousemove event listener, and switch your styles by editing the href of a link attribute: 使用mousemove事件侦听器,并通过编辑link属性的href来切换样式:

document.body.addEventListener("mousemove" event => {
    if (event.clientY >= 30) {
        document.querySelector("link").setAttribute("href", "style1.css");
    } else {
        document.querySelector("link").setAttribute("href", "style2.css");
    }
});

You can attach "mousemove" event and use 'event.clientY' to get current mouse top postion and write your requirements accordingly. 您可以附加“ mousemove”事件并使用“ event.clientY”获取当前鼠标的最高位置并相应地编写您的要求。

Here is an example below: 下面是一个示例:

 (function(){ document.body.addEventListener("mousemove", function() { if (event.clientY >= 30) { document.querySelector(".myDiv").classList.remove('class2'); document.querySelector(".myDiv").classList.add('class1'); } else { document.querySelector(".myDiv").classList.remove('class1'); document.querySelector(".myDiv").classList.add('class2'); } }); })(); 
  .myDiv { height: 200px; width: 200px; border:1px solid #f00; } .class1 { border-radius: 50%; } .class2 { border-radius: 10%; } 
 <!DOCTYPE html> <head> </head> <body> <div class="myDiv"></div> </body> </html> 

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

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