如何使三角箭头跟随鼠标的路径?

时间:2016-08-09 16:47:29

标签: jquery html css

我想在左侧或右侧的主导航滑块上制作小三角形指针,具体取决于用户将鼠标指向主标题的位置,如“主页”,“产品”,“登录”或“购物车” ”。请查看我的网站www.inpha.co

要查看我正在尝试做的实际示例,请访问此网站www.harris-active.co.uk。我已经为下面的主导航提供了CSS代码,因此您可以看到缺少的内容。请提供有关准确放置代码的位置的完整详细信息和分步说明。如果还需要jQuery,那么请提供完整的详细信息。

CSS代码:

/* Navigation
--------------------------------------------------------------------------------*/

#nav-wrap .container {
clear: both;
overflow: hidden;
position: relative;
border:none;
}

#nav-wrap table {
width:100%;
border-collapse: collapse;
border-spacing: 0;
padding:0px;
}

#nav-wrap table td {
border-collapse: collapse;
border-spacing: 0;
}

#nav-wrap .container ul {
list-style: none;
float: right;
margin-right:40px;
}

#nav-wrap .container ul li {
list-style: none;
float: left;
margin-left:40px;
position:relative;
top:1px;
}

#nav-wrap .container ul li a {
display: block;
font-family: 'Open Sans', sans-serif;
font-weight: bold;
color: #999999;
text-decoration: none;
padding: 57px 0px;
border: 0;
outline: 0;
list-style-type: none;
font-size: 16px;
}

#nav-wrap .container ul li#active a,
#nav-wrap .container ul li a:hover {
color: #fff;
background: url(nav-hover-orange.png) no-repeat center bottom;
border: 0;
}

1 个答案:

答案 0 :(得分:1)

不需要jQuery。

首先设置元素css

.trail { 
position: absolute;
height: 6px; width: 6px;
border-radius: 3px;
background: teal;

}

您必须调整目标元素的位置。

然后JS:

// dots is an array of Dot objects,
// mouse is an object used to track the X and Y position

var dots = [],
mouse = {
  x: 0,
  y: 0
};

// The Dot object used to scaffold the dots
var Dot = function() {
this.x = 0;
this.y = 0;
this.node = (function(){
var n = document.createElement("div");
n.className = "trail";
document.body.appendChild(n);
return n;
}());
 };
 // make a draw prototype function
Dot.prototype.draw = function() {
this.node.style.left = this.x + "px";
this.node.style.top = this.y + "px";
};

// you do not need this part for your purpose
for (var i = 0; i < 12; i++) {
var d = new Dot();
dots.push(d);
}

 // This is the prototype fn
function draw() {

 var x = mouse.x,
  y = mouse.y;


dots.forEach(function(dot, index, dots) {
var nextDot = dots[index + 1] || dots[0];

dot.x = x;
dot.y = y;
dot.draw();
x += (nextDot.x - dot.x) * .6;
y += (nextDot.y - dot.y) * .6;

});
}

addEventListener("mousemove", function(event) {
//event.preventDefault();
mouse.x = event.pageX;
mouse.y = event.pageY;
});

// animate() calls draw() then recursively calls itself
// everytime the screen repaints via requestAnimationFrame().
function animate() {
draw();
requestAnimationFrame(animate);
}


animate();

当然,您不会创建点,但上述内容应足以弄清楚如何将此代码应用于目标元素。

jQuery版本将更加冗长,稍后我可能会添加它。

链接:

http://codepen.io/damianocel/pen/yJEKYv