根据鼠标位置添加 Css 类

Add Css class depending on mouse position

本文关键字:Css 添加 位置 鼠标      更新时间:2023-09-26

我正在尝试根据鼠标位置将一个类添加到一组div中,最终结果将是一堵墙的人看着光标...

我已经写了一些我认为应该有效的东西,我可以addClass但它非常错误,似乎只添加一次类,而不是经常检查鼠标位置。谁能看到我哪里出错了?

this.setImageDirection = function(){
    if(mouseX >= this.imageLeft && mouseX <= this.imageRight && mouseY <= this.imageTop){
        $(this).removeClass();
        $(this).addClass("up");
    } else if(mouseX < this.imageLeft && mouseY < this.imageTop){
      $(this).removeClass();
       $("."+this.className+">.head-image").addClass("up-left");
    } else if(mouseX <= this.imageLeft && mouseY >= this.imageTop && mouseY <= this.imageBottom){
        $(this).removeClass();
       $(this).addClass("left");
    } else if(mouseX < this.imageLeft && mouseY > this.imageBottom){
        $(this).removeClass();
        $(this).addClass("down-left");
    } else if(mouseX >= this.imageLeft && mouseX <= this.imageRight && mouseY >= this.imageBottom){
        $(this).removeClass();
        $(this).addClass("down");
    } else if(mouseX > this.imageRight && mouseY > this.imageBottom){
        $(this).removeClass();
        $(this).addClass("down-right");
    } else if(mouseX >= this.imageRight && mouseY >= this.imageTop && mouseY <= this.imageBottom){
        $(this).removeClass();
        $(this).addClass("right");
    } else (mouseX > this.imageRight && mouseY < this.imageTop){
        $(this).removeClass();
        $(this).addClass("up-right");
    } 
};

工作演示

https://jsfiddle.net/cppsh7y9/

您的代码无效。请参阅此行:

} else (mouseX > this.imageRight && mouseY < this.imageTop){

它应该是:

} else if(mouseX > this.imageRight && mouseY < this.imageTop){

您正在尝试使用 $(this) 引用 jquery 元素,但this不是元素,它是HeadImage"类"的实例,因此 jquery 方法不起作用。您需要在实例化元素时保存对元素的引用,并从中添加/删除 css 类。

例如,可能是这样的:

function HeadImage(className){
   this.element = $('.' + className);
   this.className = className;
   /* rest of the function ... */
}

然后在setImageDirection方法中:

this.setImageDirection = function(){
    if(mouseX >= this.imageLeft && mouseX <= this.imageRight && mouseY <= this.imageTop){
        this.element.removeClass();
        this.element.addClass("up");
    }
    /* ... */
}