[英]Change <body> background image on <div> hover
假设我们在body标签上有一个黑白背景图片,并且希望它切换到城市天际线的背景图片,同时将鼠标悬停在div id =“ 1”上,晚上悬停在div id =“ 2”上时,仍保持相同的天际线。 我将如何处理?
我已经为此编写了一些html / css,以及“体面的” python知识,但是没有脚本语言(如javascript)的经验。 我不想复制大量的代码片段,因为我是新手并且想学习。
这是我到目前为止的内容:
/*css*/
#bg{background:url('a');
}
#header{
position:absolute;
border:double 30pt;
width:95%;
height:15%;
}
#header img{height:120px;
}
#header img:hover{
transform: rotate(-10deg);
}
#allies{
border:double 30pt;
position:relative;
width:45%;
top:250px;
}
#allies:hover ~ #bg{background:url('b');
}
#enemies{
border:double 30pt;
position:relative;
width:45%;
/*top:55px;*/
top:-67px;
left:967px;
}
#enemies:hover ~ #bg{background:url('c')
}
div img{
width:120px;
height:100px;
display:block;
margin-left:auto;
margin-right:auto;
padding-top:10px;
padding-bottom:5px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AE</title>
<link href="AE.css" rel="stylesheet" type="text/css">
</head>
<body id="bg">
<div id="header">
<a href="index.htm">
<img src="http://www.iconsdb.com/icons/preview/black/home-5-xxl.png">
</a>
</div>
<div id="allies">
<img src="http://fontmeme.com/permalink/170203/949c0c2c2c0c34c044b9b45585717a70.png">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div id="enemies">
<img src="http://fontmeme.com/permalink/170203/e8d4db59e876e5c94bd8f072137e33e2.png">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
</html>
我得到了你想要的,使用Jquery:
jQuery的:
$( "#allies" ).hover(function() {
$('body').css("background", "url(https://cdn.pixabay.com/photo/2013/04/14/20/24/water-103817_960_720.jpg");
});
$( "#enemies" ).hover(function() {
$('body').css("background", "url(http://weknowyourdreams.com/images/fire/fire-02.jpg");
});
您无法通过CSS实现此目的。 使用jQuery hover()函数。 在函数内部,您可以使用css()函数或(更好)您在css文件中定义的addClass()/ removeClass()。 https://api.jquery.com/hover/
js:
$('#allies').hover(function() {
$('#bg').addClass('newBg1');
}, function() {
$('#bg').removeClass('newBg1');
});
$('#enemies').hover(function() {
$('#bg').addClass('newBg2');
}, function() {
$('#bg').removeClass('newBg2');
});
CSS:
.newBg1 {
background-image: #your url;
}
.newBg2 {
background-image: #your url;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.