javascript文字跟随鼠标移动简易实现方法
效果图
文章图片
方法 文字跟随鼠标移动即是实时获取鼠标位置,并将文字的位置设置为鼠标的位置,用left和top即可控制文字的位置。
html
hint为存放文字的div,必须设置position它才会跟随鼠标的位置移动而移动,一般用absolute。
点我DOM
点我JQuery
js
上面是js的原生方法,下面是jquery方法,两个都可以直接调用执行。
//提示跟随鼠标移动而移动功能// DOM
function WordsFollowMouseDOM(hintwords) {
document.addEventListener("mousemove", function (e) {
var myhint = document.getElementById("hint");
myhint.style.left = e.clientX + 8 + "px";
myhint.style.top = e.clientY + 2 + "px";
switch (hintwords) {
case 1:
myhint.innerHTML = "我是文字跟随鼠标1。";
myhint.style.display = 'block';
break;
case 2:
myhint.innerHTML = "我是文字跟随鼠标2。";
myhint.style.display = 'block';
break;
default:
myhint.innerHTML = "";
myhint.style.display = 'none';
break;
}
});
}// JQuery
function WordsFollowMouseJQuery(hintwords) {
document.addEventListener("mousemove", function (e) {
var myhint = $("#hint");
$(myhint).css({
"left": e.clientX + 8 + "px",
"top": e.clientY + 2 + "px"
});
switch (hintwords) {
case 1:
$(myhint).text("我是文字跟随鼠标3。");
$(myhint).css({"display":"block"});
break;
case 2:
$(myhint).text("我是文字跟随鼠标4。");
$(myhint).css({"display":"block"});
break;
default:
$(myhint).text("");
$(myhint).css({"display":"none"});
break;
}
});
}
$("#clickme1").click(function(){
WordsFollowMouseDOM(1);
});
$("#clickme2").click(function(){
WordsFollowMouseJQuery(1);
});
完整代码为:可直接使用
文字跟随鼠标 - 锐客网
点我DOM
点我JQuery
【javascript文字跟随鼠标移动简易实现方法】
下载完整代码learning-everything/javascript/word_follow_mouse。
推荐阅读
- 事件代理
- 数组常用方法一
- 时光,是行走在文字里的眷恋
- 我的小叔
- 罗塞塔石碑的意义(古埃及文字的起源,圣书体文字是如何被破解的)
- 琉璃心
- 【散文诗】河流
- 【孩子的文字】星
- JavaScript|vue 基于axios封装request接口请求——request.js文件
- JavaScript|JavaScript: BOM对象 和 DOM 对象的增删改查