我有一个自定义的图像光标,用于我的body
和链接。
我想实现的是将光标应该过渡到链接的光标图像的链接上悬停,而不是立即更改。
目前,我有以下代码:
html {
height:100%;
}
body {
cursor:url(https://i.imgur.com/odlAwsz.png), auto !important;
width:100%;
height:100%;
background:red;
}
a {
cursor:url(https://i.imgur.com/yxX4Snm.png), auto !important;
}
<a href="#">I'm a link</a>
正如您在上面看到的,悬停时两个圆圈图标之间没有过渡<a>
.
我尝试用CSS实现这一点,但没有成功。如何使用 JavaScript 实现这一点?
以下是可以实现的方法: 以下解决方案允许您使用自定义 HTML 游标,这些游标可以在悬停特定标记时从一种状态过渡到另一种状态。
- 让我们首先创建自定义 HTML 光标:
#cursor {
width: 20px;
height: 20px;
position: absolute;
top: 0;
left: 0;
background: blue;
border-radius: 10px;
}
<div id="cursor"></div>
- 然后我们需要让这个元素跟踪实际光标的位置:
$(document).mousemove(function(e) {
const cursor = $('#cursor');
const target = $(event.target);
// update position of cursor
cursor.css('left', e.clientX-10).css('top', e.clientY-10);
});
* {
cursor: none;
}
#cursor {
width: 20px;
height: 20px;
position: absolute;
top: 0;
left: 0;
background: blue;
border-radius: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cursor"></div>
-
当
#cursor
悬停<a>
时,我们将添加一个类(.hoveredCursor
),它将改变#cursor
的初始属性(例如width
和height
)。为了不必要地在光标上添加或删除类mousemove
我们可以检查两件事: -
目标是
<a>
元素,可以用jQuery的.is
方法检查:const isLinkTag = target.is('a');
-
#cursor
是否具有类.hoveredCursor
即#cursor
已经在徘徊了。使用方法.hasClass
:const isHovered = cursor.hasClass('hoveredCursor');
-
您可以将任何属性设置为
.hoveredCursor
,当悬停时,这些属性将添加到#cursor
的初始属性中(您可能需要使用!important
来覆盖样式),例如:.hoveredCursor { width: 10px !important; height: 10px !important; }
然后设置#cursor
的transition
属性以使其平滑:
#cursor {
transition: linear height 0.2s, linear width 0.2s;
}
- 您可能会遇到的一个问题是
#cursor
妨碍event.target
意味着目标将#cursor
。这会导致一些不良行为(#cursor
将在两种状态之间来回切换......
将none
设置为#cursor
的pointer-events
将解决这个问题(事件将简单地忽略#cursor
)。
这是最终代码:
$(document).mousemove(function(e) {
const cursor = $('#cursor');
const target = $(event.target);
// update position of cursor
cursor.css('left', e.clientX-10).css('top', e.clientY-10);
const isLinkTag = target.is('a');
const isHovered = cursor.hasClass('hoveredCursor');
// toggle the cursor class if necessary
if(isLinkTag && !isHovered) {
cursor.addClass('hoveredCursor');
} else if(!isLinkTag && isHovered) {
cursor.removeClass('hoveredCursor');
}
});
$(document).mouseleave(function(e) {
const cursor = $('#cursor');
cursor.hide()
});
$(document).mouseenter(function(e) {
const cursor = $('#cursor');
cursor.show()
});
* {
cursor: none;
}
#cursor {
pointer-events: none;
width: 20px;
height: 20px;
position: absolute;
top: 0;
left: 0;
display: none;
background: blue;
border-radius: 10px;
transition: linear height 0.2s, linear width 0.2s;
}
.hoveredCursor {
width: 10px !important;
height: 10px !important;
}
a {
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cursor"></div>
<a href="#">This is a link</a>
注意:我也为文档添加了mouseenter
和mouseleave
,以便自定义光标相应地隐藏或显示。
使用这种方法的优点是它允许您在任何给定元素的两组属性之间转换(通过标签 - 这里<a>
- 甚至通过选择器)。