[英]How do you move a div element in jquery
所以基本上我有一个这样的菜单:[家,项目,声音,联系],菜单顶部有一个小圆圈。 所以我想要它,当我点击菜单项时,小圆圈移动到项目(在它上面)。
所以像这样:
到目前为止这是我的jquery:
$(document).ready(function(){
var position = 80;
$('.navP').click(function(){
// change all to black, then change the one I clicked to red
$('#indicatorBar').animate({'margin-left':'+='+position+'px'}, 1000);
$('.navP').css('color', 'white');
$(this).css('color', 'red');
});
});
我的HTML:
<div class ="menuContainer">
<span id="indicatorBar">
<i class="icon-circle"></i>
</span>
<a class="nameBanner" href="#mainPage"> Ipalibo Whyte</a>
<ul>
<li><a class="navP" href="#mainPage">Home</a></li>
<li><a class="navP" href="#projectContents">Projects</a></li>
<li><a class="navP" href="#musicContent">Sounds</a></li>
<li><a class="navP" href="#contactContent">Contact me</a></li>
</ul>
</div>
CSS:
#indicatorBar{
top: 0px;
right: 60px;
font-size: 7px;
color: #B4FF47;
}
.menuContainer{
position: fixed;
width: 100%;
top: 0%;
left: 0%;
bottom: 92%;
opacity: 0.7;
z-index:9;
background: #16161F;
animation: fadein 3s;
-moz-animation: fadein 3s; /* Firefox */
-webkit-animation: fadein 3s; /* Safari and Chrome */
-o-animation: fadein 3s; /* Opera */
非常感谢的例子,万分感谢!
这是基于您提供的代码的快速演示: http : //jsfiddle.net/k7ypa/
基本上,我只是获取被点击的元素的位置。
JavaScript的:
$('.navP').click(function () {
// move dot
var position = $(this).position().left + $(this).width()/2 - 5;
$('#indicatorBar').animate({
'margin-left': position + 'px'
}, 1000);
// change all to black, then change the one I clicked to red
$('.navP').css('color', 'white');
$(this).css('color', 'red');
});
我建议你对#indicatorBar使用绝对定位。
在菜单项的单击事件中,获取事件的目标(event.target,其中event是函数中的参数)。 现在添加到现有位置的值为:[target's position()。left + target's width()/ 2],您将获得新的位置。
注意:如果菜单项有填充/边距,请使用jQuery的outerWidth()而不是width()。 看起来有。
一个快速而肮脏的答案是
而且你已经定下来了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.