我想要发生的是,当有人将鼠标悬停在“Signature Events”、“Weddings”、“Le Coq d'Or”三个按钮之一时,它上面的 div 的背景和内容会发生变化。它上面的 div 是静态的,不是 slider 。只是一个样式化的 HTML block 。
我在上周左右才开始接触 JS,这似乎可以通过 JS 转换来完成,但我不确定。我什至不知道要搜索什么来获取这方面的信息。
谢谢!
最佳答案
您可以将数据属性与目标类和一点 jQuery 代码一起使用。
$('button').hover(
function() {
$('header').addClass($(this).attr("data-class")).text($(this).attr("data-title"));
}, function() {
$('header').removeClass($(this).attr("data-class")).text($('header').attr("data-title"));
}
);
header{
background-image: url('http://lorempixel.com/200/600/');
background-size: cover;
height: 180px;
width: 500px;
display: flex;
justify-content: center;
align-items: center;
}
header.backgroundOne{
background-image: url('http://lorempixel.com/200/600/');
}
header.backgroundTwo{
background-image: url('http://lorempixel.com/200/600/');
}
header.backgroundThree{
background-image: url('http://lorempixel.com/200/600/');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header data-title="Header Image">
Header Image
</header>
<button data-class="backgroundOne" data-title="Title One">
Change Header 1
</button>
<button data-class="backgroundTwo" data-title="Title Two">
Change Header 2
</button>
<button data-class="backgroundThree" data-title="Title Three">
Change Header 3
</button>
因此,如果您将鼠标悬停在一个按钮上,该按钮的数据类属性值将作为一个类添加到您的标题元素中。如果您停止悬停,该类将再次删除,以便显示默认图像。
关于javascript - 如何使悬停按钮更改不同元素的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45312325/