我是 HTML、CSS 和 JS/jQuery 的新手。我正在创建一个测试网站只是为了熟悉 jQuery,但似乎无法解决问题。
我在页面顶部有一个导航栏,左侧包含 Logo ,右侧包含链接。我已经设置了以下 jQuery 代码以在鼠标进入/离开时淡入淡出链接:
$(document).ready(main);
function main() {
$('.marquee').marquee({
/* pauseOnHover: true */
})
$('.nameorlogo, .navitems').mouseenter(function() {
$('.nameorlogo').fadeTo('fast', 1);
$('.navitems').fadeTo('fast', 1);
})
$('.nameorlogo, .navitems').mouseleave(function() {
$('.nameorlogo').fadeTo('fast', 0.5);
$('.navitems').fadeTo('fast', 0.5);
})
};
这是 html:
<!DOCTYPE html>
<html>
<head>
<title>JSTest1</title>
<link href="../css/style.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src='../js/jquery-3.2.0.js'></script>
<script type="text/javascript" src='../js/main.js'></script>
<script type="text/javascript" src='../js/marquee.js'></script>
</head>
<body>
<header class=topheader>
<nav class=navtop>
<div class=nameorlogo>
<h1><a href="index.html">JSTest1</a></h1>
</div>
<div>
<ul class=navitems>
<li><a href="index.html">Contact</a></li>
<li><a href="index.html">Services</a></li>
<li><a href="index.html">About</a></li>
<li><a href="index.html">Home</a></li>
</ul>
</div>
</nav>
</header>
<main>
<div class=marquee>This is a test for JavaScript</div>
</main>
</body>
</html>
我遇到的问题是当我将鼠标悬停在一个链接上时,无论是导航链接还是 Logo ,所有内容都会淡入淡出,我希望它们都是独立的。
我知道你可以在 CSS 中做到这一点,这纯粹是为了帮助我学习和理解。
感谢您的帮助。
吉姆
最佳答案
使用 this
关键字,如 $(this)
来引用当前悬停的元素
$(this).fadeTo('fast', 1);
另外,请注意 .navitems
是整个 UL 元素,而您需要定位 LI 元素。因此
$('.nameorlogo, .navitems li').mouseenter(function()
此外,还有其他类似的方法可以实现您的愿望:
使用.on()
方法
$('.nameorlogo, .navitems li').on({
mouseenter : function() {
$(this).stop().fadeTo(250, 1);
},
mouseleave : function() {
$(this).stop().fadeTo(250, 0.5);
},
});
// .stop() is here to prevent animation buildups
.nameorlogo,
.navitems li{
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=nameorlogo>
<h1><a href="index.html">JSTest1</a></h1>
</div>
<div>
<ul class=navitems>
<li><a href="index.html">Contact</a></li>
<li><a href="index.html">Services</a></li>
<li><a href="index.html">About</a></li>
<li><a href="index.html">Home</a></li>
</ul>
</div>
使用.hover()
方法
$('.nameorlogo, .navitems li').hover(function(evt) {
var isMouEnt = evt.type === "mouseenter";
$(this).stop().fadeTo(250, isMouEnt ? 1 : 0.5);
});
// .stop() is here to prevent animation buildups
.nameorlogo,
.navitems li{
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=nameorlogo>
<h1><a href="index.html">JSTest1</a></h1>
</div>
<div>
<ul class=navitems>
<li><a href="index.html">Contact</a></li>
<li><a href="index.html">Services</a></li>
<li><a href="index.html">About</a></li>
<li><a href="index.html">Home</a></li>
</ul>
</div>
关于javascript - 如何将动画应用于列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43210637/