在my previous question上扩展时,如何将div变成红色,并且鼠标悬停在div的左侧10px上时将光标变为指针,并使div变为绿色并将鼠标悬停在div的最右边10px?鼠标悬停最左边和最右边10px的元素?
1
A
回答
1
下面是基于您以前的代码/问题的代码的另一个答案。
$("div").on({
mousemove: function (e) {
var $this = $(this);
var x = e.offsetX;
var width = $(this).width();
// fix for firefox
if(typeof x === "undefined"){
x = e.pageX - $this.offset().left;
}
if (x<= 10) {
$this.css("background-color", "red");
$this.css("cursor","pointer");
}
else {
$this.css("background-color", "white");
$this.css("cursor","default");
}
if (x > (width-10)) {
$this.css("background-color", "green");
$this.css("cursor","pointer");
}
},
mouseleave: function (e) {
$(this).css("background-color", "white");
$this.css("cursor","default");
}
});
+1
这一个,虽然更长,更容易修改,以适应我的目的,并没有离开div保持颜色相同的错误。此答案已更改为最佳答案。 – Keavon
+1
@Keavon是的,我们不希望你必须自己想办法,我们会吗?)? –
1
可以使用jQuery的mousemove处理程序,如:
$('div').mousemove(function(e){
var parentOffset = $(this).parent().offset();
//or $(this).offset(); if you really just want the current element's offset
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
if(relX <= 10) $(this).css({'background-color':'red','cursor':'pointer'});
else if(relX > ($(this).width() -10)) $(this).css({'background-color':'green','cursor':'pointer'});
else
$(this).css({'background-color':'gray','cursor':'auto'});
});
相对元素定位来自this answer。
相关问题
- 1. 鼠标悬停最左边10px的元素?
- 2. 删除边界上最左边和最右边
- 3. 把最左边和最右边的单元格和表格边界之间的间距
- 4. 与左边和右边
- 5. SVG多边形的CSS鼠标悬停
- 6. 右边和左边的厚边框
- 7. 右边和左边的UIButton边框
- 8. 什么是二进制子树的最左边和最右边的节点?
- 9. 鼠标悬停元素
- 10. perl中最右边和最左边的符号与正则表达式匹配
- 11. 在鼠标悬停上添加边框
- 12. 引导 - 如何保证空格上最左边和最右边移动
- 13. 在鼠标悬停,检测元素是否在窗口的右边缘,并将元素移动 - jQuery
- 14. python中最右边的最小值元素
- 15. 将鼠标悬停在菜单项上可删除左边界。悬停时如何离开菜单边界?
- 16. 左边,上边,下边和右边的颜色渐变边框
- 17. 悬停框的动画边框(边框左侧,边框顶部)
- 18. 负边距“悬停”div落后元素
- 19. java:在鼠标悬停和鼠标悬停时突出显示dom元素
- 20. 把背景图像放在右边10px边框带边框
- 21. mogrify增加100像素的jpg图片的左边和右边?
- 22. 三个元素,一个左边,一个中心,一个右边的标题
- 23. 左边是浮动右边
- 24. 什么是最简单的方法来删除Silverlight TextBox鼠标悬停边框?
- 25. 把html悬停在右边,而在右边添加文字
- 26. RadRotator问题 - 当我们悬停在左边或右边的按钮
- 27. 对齐左边中间和右边
- 28. Wpf Dock Dock左边和Dock右边
- 29. 鼠标悬停射击用鼠标仍然和元素移动
- 30. 在同一行内,有一个中心元素和最右边的元素
新增指针部分,我的答案,因为我忘了。 –
虽然你可能不再需要这个答案,但其他人可能在将来 - 我们试图保持SO作为新用户的资源,所以我要稍微改变你的编辑 – Basic
是的,我注意到了,所以我删除了我的部分关于删除它人们发布真正的答案后。我很抱歉通过提出3个问题来创建此类垃圾邮件。 – Keavon