我是 css、html5 和 jquery 的新手。我正在尝试构建一个菜单,其中的列表项在悬停时出现和消失。正如 mplungjan 所问,代码在这里: http://jsfiddle.net/m5ab6/
HTML 是:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link
rel="stylesheet"
href="drop.css"
>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
</head>
<body>
<nav class="main">
<ul id="topbar">
<li class="droplist">Fruits
<ul class="subdrop">
<li>Apple</li>
</ul>
</li>
<li class="droplist">Vegetables
<ul class="subdrop"></ul>
</li>
</ul>
</nav>
</body>
<!-- <script src="drop.js"></script> -->
</html>
CSS 是:-
@CHARSET "UTF-8";
.main{
width: device-width;
height:200px;
}
#topbar
{
background-color: black;
color: grey;
/*display: none;*/
list-style-type: none;
}
.droplist
{
display: inline;
padding: 20px;
position: relative;
}
.subdrop{
display:none;
}
Javascript 是:-
function hoverinfunc(){
$(".subdrop").show(500);
//$("subdrop").css({"position:"})
}
function hoveroutfunc(){
$(".subdrop").hide(500);
}
$(document).ready(
$("li.droplist").hover(hoverinfunc, hoveroutfunc)
);
问题:从 Fruits/Vegetables 悬停会改变 Vegetables 的布局。通常,蔬菜放在水果的右边。但是,持续在水果/蔬菜中进进出出会导致蔬菜位于水果下方。我的要求是蔬菜的位置永远在水果的右边
我的解决方案(可能是一个天真的解决方案):我在 css 文件的 .droplist'
中添加 float:left;
。但是,正因为如此,背景颜色丢失了。
请帮助我理解我错在哪里。
最佳答案
function hoverinfunc() {
$(".subdrop", this).stop().show(100);
}
function hoveroutfunc() {
$(".subdrop", this).stop().hide(300);
}
$(function(){ // DOM ready shorthand
$("li.droplist").hover(hoverinfunc, hoveroutfunc);
});
CSS:
.main {
width: 100%;
height:200px;
}
#topbar {
background-color: black;
color: grey;
list-style: none;
}
.droplist {
position: relative;
display: inline-block; /*for padding to work*/
padding: 20px;
}
.subdrop {
position:absolute;
left:0; /* to properly align on the parent LI left */
background:black;
display:none;
padding:20px;
white-space:nowrap; /*for text to overflow parent LI size*/
}
另一种编写 JS 的简单好方法是:jsFiddle example
$("li.droplist").hover(function(){
$("> ul", this).stop().slideToggle(280);
});
如果你想根据事件类型不同地控制动画速度,这很简单:传递事件参数(.hover()
方法监听 mouseenter
和 mouseleave
) 转换为条件运算符 (?:
),例如:
$("li.droplist").hover(function( e ){
$("> ul", this).stop().slideToggle(e.type=='mouseenter'?100:300);
});
是 mouseenter
吗? (TRUE) 动画 100ms : (ELSE [is mouseleave
]) 动画 300ms
关于javascript - html布局发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23044620/