gpt4 book ai didi

javascript - jQuery。单击时更改元素位置

转载 作者:行者123 更新时间:2023-12-02 18:30:10 25 4
gpt4 key购买 nike

我有一个来自 jQuery 的问题。我想改变div onclick的位置。我有 4 个 div 和四个菜单。当我单击菜单时,我希望 div 到达第一个位置。这是html代码:

<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<link rel="stylesheet" type="text/css" href="my.css">
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui-1.10.3.custom.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<ul>
<li id= "home"><a href="#">Home</a></li>
<li id= "about"><a href="#">About</a></li>
<li id= "products"><a href="#">Products</a></li>
<li id= "services"><a href="#">Services</a></li>
<li id= "contact"><a href="#">Contact us</a></li>
</ul>

<div id = "newdiv" style="height:400px; width:700px; background-color:red; margin-left:auto; margin-right:auto; "></div>
<div id = "newdiv1" style="height:400px; width:700px; background-color:blue; margin-left:auto; margin-right:auto; "></div>
<div id = "newdiv2" style="height:400px; width:700px; background-color:yellow; margin-left:auto; margin-right:auto; "></div>
<div id = "newdiv3" style="height:400px; width:700px; background-color:green; margin-left:auto; margin-right:auto; "></div>

</body>
</html>

现在,当我单击“关于”时,我希望第二个 div 出现在第一个位置。我对jQuery不是很熟悉,我尝试用索引来做,但没有成功。我怎样才能做到这一点?

最佳答案

首先,您必须将所有 div 包装到一个元素中。我称之为 mainMan :

<div id="mainMan">
<div id="newdiv" style="height:400px; width:700px; background-color:red; margin-left:auto; margin-right:auto; "></div>
<div id="newdiv1" style="height:400px; width:700px; background-color:blue; margin-left:auto; margin-right:auto; "></div>
<div id="newdiv2" style="height:400px; width:700px; background-color:yellow; margin-left:auto; margin-right:auto; "></div>
<div id="newdiv3" style="height:400px; width:700px; background-color:green; margin-left:auto; margin-right:auto; "></div>
</div>

然后,编写一个像这样的事件处理程序,以便在单击 li 中的 a 时发生更改:

$("ul").on("click", "li a", function () {
var index = $(this).parent("li").index();
$("#mainMan").find("div:eq(" + index + ")").prependTo("#mainMan")
});

技巧是使用 index 将相应的 div:eq() 选择器匹配,然后使用 prepend 会将所选元素移动到前面。

您需要做的最后一件事是在样式表中为常见样式添加 css 样式,并将 bgcolor 单独保留为内联。

<div id="mainMan">
<div id="newdiv" style=" background-color:red;"></div>
<div id="newdiv1" style="background-color:blue;"></div>
<div id="newdiv2" style="background-color:yellow;"></div>
<div id="newdiv3" style="background-color:green;"></div>
</div>

还有你的CSS:

#mainMan > div {
height:400px;
width:700px;
margin-right:auto;
}

演示:http://jsfiddle.net/hungerpain/gsMyA/1/

关于javascript - jQuery。单击时更改元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17878104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com