[英]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.