我正在尝试更改以在悬停时更改图片。这是我到目前为止所做的:
.HTML
<div class="picture">
<div class="text">
<h1>Hey everyone!</h1>
</div>
</div>
.CSS
.picture{
width: 200px;
height: 200px;
background-image: url("https://www.w3schools.com/css/trolltunga.jpg");}.text{
background-color: rgba(255,0,0,0.8);
width:200px;
height: 200px;
display: none;}
JavaScript
$(".picture").hover(function(){
$(this).children(".text").fadeToggle();});
jQuery (更改背景/显示文本):
.HTML:
<div class="picture">
<div class="text">
<h1>Hey everyone!</h1>
</div>
</div>
.CSS:
.picture {
width: 200px;
height: 200px;
background-image: url("https://www.w3schools.com/css/trolltunga.jpg");
}
.text {
background-color: rgba(255, 0, 0, 0.4);
width: 200px;
height: 200px;
display: none;
}
.JS:
$(".picture").hover(function() {
$(this).animate({
opacity: 0.7
}, 100, function() {
$(this).css("background-image", "url('https://upload.wikimedia.org/wikipedia/en/2/27/Bliss_%28Windows_XP%29.png')");
});
$(".text").fadeToggle();
}, function() {
$(this).animate({
opacity: 0.7
}, 100, function() {
$(this).css("background-image", "url('https://www.w3schools.com/css/trolltunga.jpg')");
});
$(".text").fadeToggle();
});
https://jsfiddle.net/wlecki/28vschr1/
仅 CSS 解决方案:
.HTML:
<div class="picture">
<div class="text">
<h1>Hey everyone!</h1>
</div>
</div>
.CSS:
.picture {
width: 200px;
height: 200px;
background-image: url("https://www.w3schools.com/css/trolltunga.jpg");
}
.text {
background-color: rgba(255, 0, 0, 0.4);
width: 200px;
height: 200px;
opacity: 0;
}
.picture:hover {
background-image: url("https://upload.wikimedia.org/wikipedia/en/2/27/Bliss_%28Windows_XP%29.png");
}
.picture:hover .text {
opacity: 1;
}
https://jsfiddle.net/wlecki/9vnokdec/
它工作正常,如您在此示例中所示:
$(".picture").hover(function() {
$(this).children(".text").fadeToggle();
});
.picture {
width: 200px;
height: 200px;
background-image: url("https://www.w3schools.com/css/trolltunga.jpg");
}
.text {
background-color: rgba(255, 0, 0, 0.8);
width: 200px;
height: 200px;
display: none;
}
<div class="picture">
<div class="text">
<h1>Hey everyone!</h1>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>