JSFiddle - React, Tailwind, and code Playground
http://stackoverflow.com/questions/19348112/javascript-rectangle-follow-cursor-in-menu/
HTML
<ul id="menu">
<li>Первый пункт</li>
<li><a href="test">Второй пункт точка</a></li>
<li>Третьий пункт точка и запятая</li>
<li>Четвёртый пункт</li>
</ul>
<div id="d1"></div>
CSS
#menu, #menu li {
position:relative;
background-color:transparent;
}
#d1 {
z-index:-10;
}
ul {
border:2px solid red;
background:#CC9;
width:650px;
}
li {
display:inline-block;
border:1px solid blue;
}
#d1 {
position:absolute;
background:red;
left:15px;
top:17px;
width:135px;
height:25px;
z-index:-10;
}
JavaScript
(function () {
var rect, rect1; // rectangles
var shadow; // shadow div
var bpos; // begin position
var epos; // end position
var width, shadowWidth;
var step; // animation step 1..50
var timer = null;
function getOffset(elem) {
var offsetLeft = 0;
var offsetTop = 0;
do {
if (!isNaN(elem.offsetLeft)) {
offsetLeft += elem.offsetLeft;
offsetTop += elem.offsetTop;
}
} while (elem = elem.offsetParent);
return { left: offsetLeft, top: offsetTop };
// http://stackoverflow.com/questions/5598743/finding-elements-position-relative-to-the-document
}
function animateRect() {
step++;
if (step > 50) {
clearInterval(timer);
timer = null;
return;
}
var t = bpos.t + Math.round((epos.t - bpos.t) * step / 50);
var l = bpos.l + Math.round((epos.l - bpos.l) * step / 50);
var w = shadowWidth + Math.round((width - shadowWidth) * step / 50);
shadow.style.top = t + "px";
shadow.style.left = l + "px";
shadow.style.width = w + "px";
console.log(t, l, w, bpos, epos, step, epos.t - bpos.t);
}
function highlightMenu(e) {
e = e || window.event; // for IE8,7
var item = e.target || e.srcElement; // for IE8,7
if (timer) {
clearInterval(timer);
}
step = 0;
rect = getOffset(item);
width = item.offsetWidth;
epos = {
t: rect.top,
l: rect.left
};
rect1 = getOffset(shadow);
shadowWidth = shadow.offsetWidth;
bpos = {
t: rect1.top,
l: rect1.left
};
timer = setInterval(animateRect, 5);
}
function init() {
var menu = document.getElementById('menu');
var items = menu.getElementsByTagName('li');
for (var i = 0; i < items.length; i++)...