根据鼠标位置添加 Css 类
Add Css class depending on mouse position
我正在尝试根据鼠标位置将一个类添加到一组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");
}
/* ... */
}
相关文章:
- jquery css添加IE8过滤器
- 如何将 CSS 添加到 CKEDITOR
- 将 JavaScript 和 CSS 添加到页脚
- 如何将动画 css 添加到引导下拉列表
- 将 css 添加到 jquery 子元素
- 如何使用jquery或javascript将css添加到伪元素
- 将悬停CSS添加到用javascript处理的表单元格中
- jQuery - 将 css 添加到 localStorage 变量
- 将内联 CSS 添加到 Timnymce 中的 body
- 通过JavaScript CSS添加元素后,hack不起作用
- 将 CSS 添加到文档加载后创建的元素
- 如何使用 JS 或 CSS 添加透明度层
- 使用 jQuery 将 CSS 添加到正文中的 head 标签
- 将 CSS 添加到 Javascript 小部件
- jQuery没有't将CSS添加到附加的输入中
- 将自定义CSS添加到使用Web视图呈现的HTML页面中
- 如何将css添加到json响应中
- 将css添加到已经存储在变量中的jQuery对象的伪元素中
- 将css添加到html中表的动态添加行中
- 为什么jQuery(document).ready不工作?/如何将CSS添加到jQuery中的元素中